Валера Стригун Валера Стригун - 3 months ago 15
C# Question

How to insert and update documents info into mongodb?

I am kind of newbie in MongoDB.
I have a list of documents. Some of them are already in database.
I need to insert or update data in Mongo using C#.
What is the best method to do it?

Thanks for answers.

Answer

The easiest way would be to use the upsert option in the update command

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

So in C# something like

collection.Update(
    Query.EQ("someproperty", propertyValue),
    Update.Replace(newObject),
    UpdateFlags.Upsert);

The above command replaces the ENTIRE document so use with caution. You can also use the <update> part of the command to update individual fields like this

var update = Builders<BsonDocument>.Update.Set("someProperty", newValue);