MongoDB使用一个集合中的一系列ID来根据另一个集合的ID进行过滤结果
假设有一个MongoDB集合Colla
。说colla
具有以下三个文档:
{"_id": "1", "name": "Bob"},
{"_id": "2", "name": "John"},
{"_id": "3", "name": "Will"}
假设还有另一个MongoDB Collection CollB
具有以下文档:
{
"_id": "1",
"foo": {
"arr": ["1", "3"]
}
}
MongoDB中是否有办法查询collb
foo.arr
数组内容([“ 1”],[“ 3”]
),并使用它来检索文档Colla
具有这些_id
值,以产生以下结果:
{"_id": "1", "name": "Bob"},
{"_id": "3", "name": "Will"}
Suppose there is a MongoDB Collection CollA
. Say CollA
has the following three Documents:
{"_id": "1", "name": "Bob"},
{"_id": "2", "name": "John"},
{"_id": "3", "name": "Will"}
Let's say there is another MongoDB Collection CollB
which has the following Document:
{
"_id": "1",
"foo": {
"arr": ["1", "3"]
}
}
Is there a way in MongoDB to query CollB
for the foo.arr
array contents (["1"],["3"]
) and use it to retrieve the Documents in CollA
which have these _id
values, to produce the following result:
{"_id": "1", "name": "Bob"},
{"_id": "3", "name": "Will"}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从
collb
执行简单$查找
。在$ lookup
结果 $ undind 之后,使用$替换
$ lookup结果是 mongo playground 供您参考。
Perform a simple
$lookup
fromCollB
. Use$replaceRoot
with the$lookup
result after$unwind
Here is the Mongo Playground for your reference.
查询
_id
带有数组foo.arr
和限制1的字段,我们只是在意是否加入无需将许多文档保存
存储如果您只需要1个collb的特定文档,我认为从collb开始像雷的答案一样有意义,但是在
$ match
$ yougp $ lookup 之前,请添加$ match
。 collb)playmongo
Query
_id
field with arrayfoo.arr
and limit 1, we just care if joined(no need to save many documents to memory)
*this will keep from collA all the documents that their
_id
, are in any array in collB (if you want only for 1 specific document of collB i think starting from collB like ray's answer makes more sense, but add a$match
also before the$lookup
for the 1 member of collB)Playmongo