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?
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.
I ran into what I believe to be the same issue - how to retrieve the ObjectId from an unknown mongo document. I have built a generic datacontext and needed the _id within my update and delete methods. Having found your question while searching for an answer on how to do this, I decided to post what finally worked for me.
private BsonValue GetId<TEntity>(TEntity entity)
{
var bsonDoc = entity.ToBsonDocument();
return bsonDoc.GetElement("_id").Value;
}
I then use it something like this:
var id = GetId<TEntity>(entity);
var filter = builder.Eq("_id", id);
var doc = collection.Find(filter).SingleOrDefault();
Hope this helps.
You can use find() method to achieve this.
db.collection.find() method does not return actual document but it return cursor to the document. by iterating through the cursor you will the fields within that document.
Code :
var cursor=db.collection.find()
var objectId= cursor.next()._id
above statement get the value of ObjectId from current cursor instance. if you to retrieve all objectId then by iterating through cursor you will get all the values of ObjectId.
To find document directly using objectId received in first step you can use following code snippet:
db.collection.find( { "_id": objectId},{ fields Of Your Choice } )
来源:https://stackoverflow.com/questions/24557580/how-to-return-the-objectid-or-id-of-an-document-in-mongodb-and-error-in-need