mongodbobjectidnosql

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" : "dessa_beca@hotmail.com", "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?


Solution

  • 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.