Get _id of an inserted document in MongoDB?

When you insert an object into the mongodb, mongo will update the object with the internal ID.

So if

data = {
  title: "Howdy"
}

Then when we insert the data object into the db

db.collection('collectionName', function(err, collection) {
  collection.insert(data);
  console.log(data._id); // <- The mongodb id is now set on the item
});

As the comment above, add the fild ID in your model with

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string id { get; set; }

using:

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

and then when you insert the object, mongo return the ID of the document into the fild ID of the model.


The Insert method automatically sets the property that is declared as the BSON ID of the model.

If declared as follows...

[BsonId]
public ObjectId Id { get; set; }

... then the Id field will contain the default (new, unique) BSON ID of the object after inserting the object into a collection:

coll.Insert(obj);
// obj.Id is now the BSON ID of the object