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

AndBecaPine picture AndBecaPine · Jul 3, 2014 · Viewed 50.6k times · Source

I have a document in MongoDB and I would like to get the ObjectId of this document, but I did not find so far a method that does this to me.

Example of query :

 user= db.users.find({userName:"Andressa"})

This returns this :

 { "_id" : ObjectId("53b1c579bdf3de74f76bdac9"), "userid" : 0, "userName" : "Andressa", "userEmail" : "[email protected]", "teams" : [ 1, 2, 3 ] }

I want get the ObjectId to do another query .

Example:

 userID =  `user._id();` //but this does not work, of course, its an example

So, I could user the ObjectId to do another query like this:

 userFind = db.users.find({_id: userID})

UPDATE: This code :

 db.teams.find({_id:{$in: user.teams}})

returns this error:

error: {
    "$err" : "Can't canonicalize query: BadValue $in needs an array",
    "code" : 17287

Does someone know it?

Answer

kranteg picture kranteg · Jul 3, 2014

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/