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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With