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

I have a document in MongoDB, and I would like to get the ObjectId of this document, but still have not found a method that does this for me.

Request example:

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

This returns the following:

 { "_id" : ObjectId("53b1c579bdf3de74f76bdac9"), "userid" : 0, "userName" : "Andressa", "userEmail" : "dessa_beca@hotmail.com", "teams" : [ 1, 2, 3 ] }

I want ObjectId to execute another request.

Example:

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

So, I could query ObjectId for another query:

 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 anyone know about this?

+4
source share
4 answers

I understood! In fact, I could do this with this code:

Instead simply:

user = db.users.findOne({userName:"And"})

I just:

  var user = db.users.findOne({userName:"And"})

and

  user._id 

returns ObjectId ("someId"), if I want to save it in some variable, I do:

var Id = user._id. 

, .

+3

mongo _id:

user._id.str

user._id.toString()

. : http://docs.mongodb.org/manual/reference/method/ObjectId.valueOf/

+2

, , , - ObjectId mongo. datacontext _id . , , , , .

private BsonValue GetId<TEntity>(TEntity entity)
{
    var bsonDoc = entity.ToBsonDocument();
    return bsonDoc.GetElement("_id").Value;
}

:

 var id = GetId<TEntity>(entity);
 var filter = builder.Eq("_id", id);
 var doc = collection.Find(filter).SingleOrDefault();

, .

+1

find().

db.collection.find() , . .

:

    var cursor=db.collection.find()

    var objectId= cursor.next()._id

above, the operator gets the ObjectId value from the current cursor instance. if you want to get all objectId, then iterating through the cursor you get all the ObjectId values.

To find a document directly using the objectId obtained in the first step, you can use the following code fragment:

       db.collection.find( { "_id": objectId},{ fields Of Your Choice } )
0
source

Source: https://habr.com/ru/post/1547036/


All Articles