MongoDB Collection A contains documents with an array with some document ids of collection B:
Collection A:
{
some_ids_of_b: ["id1", ...]
}
Collection B:
{
_id: "id1"
},
{
_id: "id2"
},
...
How do I query all documents from B whose _ids
are NOT in contained in the some_ids_of_b
arrays of documents of A?
3
Answers
One option is:
See how it works on the playground example
Simple lookup from collection B to A and filter to keep only those documents where you don’t find any matches.
Demo
You can do it with Aggregation Framework:
$group
and$addToSet
– To get all$some_ids_of_b
from all the documents inA
collection.$set
with$reduce
– To create an array with all unique values of the IDs from theB
collection.$lookup
– To fetch the documents from theB
collection, where the_id
of the document is not present in the$b_ids
array.$project
– To project data as expected output.Working Example