Find mongodb docs based on array of object contains two fields
simple $or
db.collection.aggregate([
{
"$match": {
"$or": [
{
"user_id": 1,
"lead_id": 901
},
{
"user_id": 2,
"lead_id": 902
}
]
}
}
])
mongoplayground
node
const reqArr = [
{
"user_id": 1,
"lead_id": 901,
},
{
"user_id": 2,
"lead_id": 999,
}
]
Model.find({ "$or": reqArr})
The simplest way to do the above would be this:
const results = await Promise.all(reqArr.map(req => {
const { user_id, lead_id } = req;
return Model.findOne({ user_id, lead_id });
}));
We map over each item in reqArr
. For each item (req
), we destructure into two variables user_id
and lead_id
.
We then query for a single document (I assume there is only one document for each user_id
and lead_id
pair, otherwise this will need to be slightly adjusted.
We then return the findOne
promise, resulting in an array of promises which we pass into Promise.all
to await them all asynchronously.
This should result flat array of results that match the lead_iq
/user_id
pairs in reqArr
.
If some of these combos aren't present in the database, those elements of the array will be undefined
and you can go on to handle those however you need to.