If I want to read and write mongo data with a POCO
public class Thingy
{
public string Foo {get;set;}
}
...
coll.Insert(new Thing(Foo = "hello"));
When I read back I get a failure saying that _id is an unexpected attribute (which it is). So then I added a field called _id to the class. Now the insert doesnt work saying that the _id field cannot be null. A tried BsonIgnoreIfNull attribute, that didnt work.
When you insert an object, if it doesn’t have an
_idfield then the driver adds one and sets it to a 12-byte MongoDB ObjectId value.You just need to add an
Idproperty to your POCO, which will be deserialised from_id:Or, if you’d like to delegate another property to map onto
_idthen you can decorate it with theBsonIdAttribute, like this:The
_idfield doesn’t have to be an MongoDBObjectId, you can set it to any value of any data type (except an array), it just needs to be unique within the collection.