mongodb:给定键列表,检查集合中是否有与密钥匹配的文档
假设我在用户集合中有以下数据:
{
"_id": "1",
"name": "Robert"
},
{
"_id": "2",
"name": "David"
},
{
"_id": "3",
"name": "Sam"
},
{
"_id": "4",
"name": "Michael"
}
以及给定的密钥列表:[“ 1”,“ 3”,“ 5”,“ 7”]
我期望的是检查每个键是否在集合中具有匹配的文档。因此,结果就是这样:
{
"_id": "1",
"matched": true
},
{
"_id": "3",
"matched": true
},
{
"_id": "5",
"matched": false
},
{
"_id": "7",
"matched": false
}
如何使用单个查询来实现此结果?感谢任何帮助,谢谢。
Let's say I have the following data in the User collection:
{
"_id": "1",
"name": "Robert"
},
{
"_id": "2",
"name": "David"
},
{
"_id": "3",
"name": "Sam"
},
{
"_id": "4",
"name": "Michael"
}
And a given list of keys: ["1", "3", "5", "7"]
What I expect is a check for each key whether it has a matched document in the collection. So the result would be like this:
{
"_id": "1",
"matched": true
},
{
"_id": "3",
"matched": true
},
{
"_id": "5",
"matched": false
},
{
"_id": "7",
"matched": false
}
How do I achieve this result using a single query? I would appreciate any helps, thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该解决方案需要在用户集合中至少存在1个文档,
您可以通过使用
$ Untind
使用给定的_id
s创建文档。然后执行$查找
并检查结果数组的大小。这是 mongo playground 供您参考。
This solution requires at least 1 document exists in the User collection
You can create the documents with your given
_id
s by using$unwind
. Then perform a$lookup
and check for the size of result array.Here is the Mongo playground for your reference.