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"}
2
Answers
Perform a simple
$lookup
fromCollB
. Use$replaceRoot
with the$lookup
result after$unwind
Here is the Mongo Playground for your reference.
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