gpt4 book ai didi

mongodb - 如何返回 MongoDB 中文档的 ObjectId 或 _id?和错误 "$in needs an array"

转载 作者:行者123 更新时间:2023-12-02 01:54:41 24 4
gpt4 key购买 nike

我在 MongoDB 中有一个文档,我想获取该文档的 ObjectId,但到目前为止我还没有找到对我执行此操作的方法。

查询示例:

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

这将返回:

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

我想要获取 ObjectId 来执行另一个查询。

示例:

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

因此,我可以使用 ObjectId 执行另一个查询,如下所示:

 userFind = db.users.find({_id: userID})

更新: 此代码:

 db.teams.find({_id:{$in: user.teams}})

返回此错误:

error: {
"$err" : "Can't canonicalize query: BadValue $in needs an array",
"code" : 17287

有人知道吗?

最佳答案

在 mongo shell 中,您可以使用它来检索 _id :

user._id.str

user._id.toString()

查看文档:http://docs.mongodb.org/manual/reference/method/ObjectId.valueOf/

关于mongodb - 如何返回 MongoDB 中文档的 ObjectId 或 _id?和错误 "$in needs an array",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24557580/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com