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

放肆的年华 提交于 2019-11-30 13:41:54

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.

You can use find() method to achieve this.

db.collection.find() method does not return actual document but it return cursor to the document. by iterating through the cursor you will the fields within that document.

Code :

    var cursor=db.collection.find()

    var objectId= cursor.next()._id

above statement get the value of ObjectId from current cursor instance. if you to retrieve all objectId then by iterating through cursor you will get all the values of ObjectId.

To find document directly using objectId received in first step you can use following code snippet:

       db.collection.find( { "_id": objectId},{ fields Of Your Choice } )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!