When you insert an object, if it doesn't have an _id
field then the driver adds one and sets it to a 12-byte MongoDB ObjectId value.
You just need to add an Id
property to your POCO, which will be deserialised from _id
:
public class Thingy
{
public ObjectId Id { get; set; }
}
Or, if you'd like to delegate another property to map onto _id
then you can decorate it with the BsonIdAttribute
, like this:
[BsonId]
public ObjectId MyKey { get; set; }
The _id
field doesn't have to be an MongoDB ObjectId
, you can set it to any value of any data type (except an array), it just needs to be unique within the collection.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…