In this mongo playground I have two collections: vulns
and tracker
.
I would like a query that can return a list of vulns that do not appear in tracker against a specific customerId
.
Essentially I’d like to create a list of advisoryIds
as an array for the $nin
expression – Mongo Playground.
This query is equivalent to what should be returned:
db.vulns.find({
"advisoryId": {
$nin: [
"44444",
"55555"
]
}
})
And I was able to get those values using a projection:
db.tracker.find({
"customerId": "12345"
},
{
"advisory.advisoryId": 1,
_id: 0
})
I just need to find a way to combine those queries.
2
Answers
Okay, using your example where you
find()
the advisories for"customerId": "12345"
and then lookup the one’s which are missing for that customerId – presumably that’s how you want the combination to occur.This pipeline will lookup up each
advisoryId
fromvulns
in thetrackers
collection and additionally match on thecustomerId
. Whenever the lookup presents no results ie an empty array, those are the missing advisories:Mongo Playground
Here’s another way to do it by first
"$match"
ing in thetracker
collection, collecting the uniqueadvisory.advisoryId
s into an array, and then"$lookup"
the non-matching docs invulns
.Comments are in the pipeline.
Try it on mongoplayground.net.