Reputation: 1588
Following query gives me in return objects that are present in DB and matches one of the ids in the list :
db.intervention.find( { _id: { $in: [ ObjectId("5f7fc2c3e21da01ffe711e48"), ObjectId("5f7fc255555da01ffe711e48") ] } } )
What I need is the contrary : to pass a list of ids, and get in response a list of ids that could not be found in DB.
Example : In DB I have ["A", "B", "C", "D", "E"]
Query :
db.intervention.find( { _id: { $something: ["D", "E", "F", "G"] } })
What I want in response is ["F", "G"] -> id that are in the list (in the query) but not in DB.
I'm new to Mongo and have no idea about how to achieve that.
Many Thx
Upvotes: 1
Views: 1178
Reputation: 171
This will do the job. But you'll have to supply the Array of Ids 2 times in the query. Suppose you have ids. [84, 75, 76, 70, 71, 50, 12]. And Database don't have 50 & 12 in Database. Then..
db.intervention.aggregate([
{
$match: {
_id: {$in: [84, 75, 76, 70, 71, 50, 12]}
}
},
{
$group: {
_id: null,
foundIds: {$push: "$_id"}
}
},
{
$project: {
notFoundIds: {$setDifference: [ [84, 75, 76, 70, 71, 50, 12], "$foundIds"]}
}
}
])
This will result:
{
"_id" : null,
"notFoundIds" : [
50,
12
]
}
Upvotes: 2