How to return the ObjectId or _id of an document in MongoDB? and error "$in needs an array"

In the mongo shell you can use this to retrieve the _id :

user._id.str

or

user._id.toString()

See documentation : http://docs.mongodb.org/manual/reference/method/ObjectId.valueOf/


I got it! Actually , I could do it by this code:

Instead of putting just :

user = db.users.findOne({userName:"And"})

I did just :

  var user = db.users.findOne({userName:"And"})

and

  user._id 

returns the ObjectId("someId") , if I want to keep it in some variable I do:

var Id = user._id. 

About the second question, I dont know.


I ran into what I believe to be the same issue - how to retrieve the ObjectId from an unknown mongo document. I have built a generic datacontext and needed the _id within my update and delete methods. Having found your question while searching for an answer on how to do this, I decided to post what finally worked for me.

private BsonValue GetId<TEntity>(TEntity entity)
{
    var bsonDoc = entity.ToBsonDocument();
    return bsonDoc.GetElement("_id").Value;
}

I then use it something like this:

 var id = GetId<TEntity>(entity);
 var filter = builder.Eq("_id", id);
 var doc = collection.Find(filter).SingleOrDefault();

Hope this helps.