Deserialized The Ramblings of a Web Architect

12Jul/101

ObjectID’s with MongoDB and the mongodb-csharp driver

Posted by Bryan Migliorisi

I mist say, the latest release of mongodb-csharp is rather awesome.  Typed collections and LINQ support mean I can worry more about my application than about the data layer.

Here is an example of using typed collections:

public class Customer
{
	public Oid Id { get; set; }
	public string Name { get; set; }
	public CustomerBillingInfo Billing { get; set; }
	public List Depts { get; set; }
}

public void AddCustomer(Customer customer) {
	...(code removed for simplicity)...
	IMongoCollection collection = database.GetCollection();
	collection.Save(customer);
}

Gotcha: Beware of the ID property!

One thing that threw me off when I began using the typed collections was that I had defined my ID property as “_id” because That is what MongoDB uses internally.  While this made sense to me, the mongod process kept throwing errors whenever I tried the following:

...(code removed for simplicity)...
IMongoCollection<customer> collection = database.GetCollection<customer>();
Customer customer = collection.Linq().First(c => c.Name == "test customer");
customer.Name = "A new name!";
collection.Save(customer);

The error looked something like this:

Fri Jun 25 10:43:14 Exception 11000:E11000 duplicate key error index: test06.Customer.$_id_  dup key: { : ObjId(4c24c07a189cf31bd4000002) }
Fri Jun 25 10:43:14    Caught Assertion in insert , continuing
Fri Jun 25 10:43:14 insert test06.Customer exception userassert:E11000 duplicate key error index: test06.Customer.$_id_  dup key: { : ObjId(4c24c07a189cf31bd4000002) } 21ms

It was driving me crazy for days before I realized that the driver was doing some magic – the POCO object needed its ID to be named “Id” instead of “_id” an as soon as I changed that – it started working properly.