Lets say I have an array ['123', '456', '789']
I want to Aggregate and look through every document with the field books
and only return the values that are NOT in any documents. For example if ‘123’ is in a document, and ‘456’ is, but ‘789’ is not, it would return an array with [‘789’] as it’s not included in any books
fields in any document.
.aggregate( [
{
$match: {
books: {
$in: ['123', '456', '789']
}
}
},
I don’t want the documents returned, but just the actual values that are not in any documents.
2
Answers
Here’s one way to scan the entire collection to look for missing book values.
Example output:
Try it on mongoplayground.net.
Based on @rickhg12hs’s answer, there is another variation replacing
$unwind
with$reduce
, which considered less costly. Two out of Three steps are the same:Try it on mongoplayground.net.