Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 210
AndBecaPine Avatar asked Jul 03 '14 15:07

AndBecaPine


2 Answers

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/

like image 89
kranteg Avatar answered Sep 28 '22 08:09

kranteg


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.

like image 39
AndBecaPine Avatar answered Sep 28 '22 09:09

AndBecaPine