如何在 MongoDB 中返回文档的 ObjectId 或 _id?和错误“$in 需要一个数组”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24557580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return the ObjectId or _id of an document in MongoDB? and error "$in needs an array"
提问by debeka
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.
我在 MongoDB 中有一个文档,我想获取该文档的 ObjectId,但到目前为止我还没有找到对我执行此操作的方法。
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 .
我想让 ObjectId 做另一个查询。
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:
所以,我可以使用 ObjectId 来做另一个这样的查询:
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?
有人知道吗?
采纳答案by debeka
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:
返回 ObjectId("someId") ,如果我想将它保留在某个变量中,我会这样做:
var Id = user._id.
About the second question, I dont know.
关于第二个问题,我不知道。
回答by kranteg
In the mongo shell you can use this to retrieve the _id
:
在 mongo shell 中,您可以使用它来检索_id
:
user._id.str
or
或者
user._id.toString()
See documentation : http://docs.mongodb.org/manual/reference/method/ObjectId.valueOf/
请参阅文档:http: //docs.mongodb.org/manual/reference/method/ObjectId.valueOf/
回答by GeekerMode
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.
我遇到了我认为相同的问题 - 如何从未知的 mongo 文档中检索 ObjectId。我已经构建了一个通用数据上下文,并且在我的更新和删除方法中需要 _id。在寻找有关如何执行此操作的答案时发现了您的问题,我决定发布最终对我有用的内容。
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.
希望这可以帮助。
回答by DragonFire
Try this (For Node v12.16.3 / MongoDB MongoDB v4.2.6)
试试这个(对于 Node v12.16.3 / MongoDB MongoDB v4.2.6)
// find if a value exists
collection.find({ "criteria1": value1, "criteria2": value2 }).toArray
(function(err, doc) {
if (err) {
console.log('Error, Please Try Again');
}
else if (doc.length === 0) {
console.log('Does Not Exist');
} else {
console.log(doc);
console.log(doc[0]._id)
}
});
回答by DanglingPointer
You can use find() method to achieve this.
您可以使用 find() 方法来实现这一点。
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.
db.collection.find() 方法不返回实际的文档,而是将光标返回到文档。通过遍历光标,您将获得该文档中的字段。
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.
上述语句从当前游标实例中获取 ObjectId 的值。如果您要检索所有 objectId,那么通过遍历游标,您将获得 ObjectId 的所有值。
To find document directly using objectId received in first step you can use following code snippet:
要使用第一步中收到的 objectId 直接查找文档,您可以使用以下代码片段:
db.collection.find( { "_id": objectId},{ fields Of Your Choice } )