Geeks With Blogs
AzamSharp Some day I will know everything. I hope that day never comes.

The ObjectID is assigned to each document when the document is persisted in the MongoDb database. The ObjectID is a unique ID to distinguish between different documents. The ObjectID is kept in the field/attribute called “_id”. This attribute is very important when fetching and updating the records. When using MongoDb with C# driver I usually create a property called “_id”. This property maps directly with the _id field of the MongoDb storage system.

Let’s say you do not have _id in your C# entity class and you want to update couple of fields for that class. Here is a small implementation:

   var customer = customers.FindOne(new Document()
 {{"FirstName", "Mohammad"}}).ToClass<Customer>();

            customer.UserName = "azamsharp";
            customer.Email = "azamsharp@gmail.com"; 
            customers.Save(customer.ToDocument());

The above code will successfully pull the customer document and convert to the appropriate class but it will not update the existing customer document. It will go ahead and create a new document. The reason is that the Save method will look for _id field and if it is not found then a new record is inserted.

You can however use the obsolete Update method and pass your custom fetching strategy as shown in the code below:

 customers.Update(customer.ToDocument(),
 new Document(){{"CustomerId",customer.CustomerId}});

 

The above code works perfectly but it does adds more to the picture. Think of _id as the MongoDb convention and use it instead of working around it. Posted on Tuesday, August 31, 2010 8:18 AM | Back to top


Comments on this post: The ObjectID _id When Updating Entities in MongoDb

# re: The ObjectID _id When Updating Entities in MongoDb
Requesting Gravatar...
Great explanation and easy to impement. Thanks for sharing.
Left by Tony on Sep 15, 2010 5:56 PM

Your comment:
 (will show your gravatar)


Copyright © Mohammad Azam | Powered by: GeeksWithBlogs.net