The simplest way is to let the driver assign the Id value
automatically and just check it afterwards:
var document = new BsonDocument { { "x", 1 }, { "y", 2 } };
collection.Insert(document);
var id = document["_id"].AsObjectId;
If you want to generate the Id yourself, the simplest way is:
var id = ObjectId.GenerateNewId();
var document = new BsonDocument { { "_id", id }, { "x", 1 },
{ "y", 2 } };
collection.Insert(document);
A few notes on your sample code:
- ObjectId is a value type (a C# struct)
- new ObjectId() creates an ObjectId of all zeros (or use
ObjectId.Empty)
- use ObjectId.GenerateNewId() to generate a new ObjectId
- SetDocumentId is not normally called by client code, just assign a
value to document["_id"]
- When Insert generates a new Id in you pa variable it doesn't change
your oid variable
On Apr 19, 12:30 am, Scott Hernandez <
scotthernan...@gmail.com> wrote:
> Both ways work in java, and here (and pretty much all the drivers for
> that matter).
>