I am trying to perform an or query in MongoDB.
I have two array
firstNames = ['John', 'Tim','Joey']
lastNames = ['Alex', 'Smith', 'Mac']
I want to perform a query like
{$or: [{firstName: 'John', lastName: 'Alex'}, {firstName: 'John', lastName: 'Smith'}, {firstName: 'John', lastName: 'Mac'}, {firstName: 'Tim', lastName: 'Alex'} ... ]}
I tried
1.
Users.find({firstName: {$in: firstNames}, lastName: {$in: lastNames} })
Users.find({$or:[{firstName: {$in: firstNames}}, {lastName: {$in: lastNames} }]})
but this is wrong I guess. Can someone provide a better solution to this?
You can create array of tuples using $zip. $match by $in to find expected records.
db.collection.aggregate([
{
"$addFields": {
"names": {
"$zip": {
"inputs": [
[
"John",
"Tim",
"Joey"
],
[
"Alex",
"Smith",
"Mac"
]
]
}
}
}
},
{
"$match": {
$expr: {
"$in": [
[
"$firstName",
"$lastName"
],
"$names"
]
}
}
},
// cosmetics
{
"$project": {
names: false
}
}
])
Here is the Mongo playground for your reference.