Reputation: 71
I have following documents
users = [
{ name: 'kiran', age: 22, location: 'pune' },
{ name: 'rahul', age: 23, location: 'mumbai' },
{ name: 'amit', age: 25, location: 'nashik' },
{ name: 'abhijeet', age: 26, location: 'pune' }
]
I have to find users based on multiple locations, So I have input array locations = ["pune", "nashik"]
.
It should result in three documents except one whose name is rahul
because input array doesn't match his location.
output = [
{ name: 'kiran', age: 22, location: 'pune' },
{ name: 'amit', age: 25, location: 'nashik' },
{ name: 'abhijeet', age: 26, location: 'pune' }
]
So how can I achieve this with MongoDB.
thanks for any help.
Upvotes: 0
Views: 114
Reputation: 13103
You can use $in operator.
If users
are stored as sub-document, use this approach.
db.users.find({
location: {
$in: [
"pune",
"nashik"
]
}
})
db.users.aggregate([
{
$match: {
location: {
$in: [
"pune",
"nashik"
]
}
}
}
])
EDIT: Nodejs code
let query = [];
let locations = ['pune', 'nashik'];
query.push({
'$match': { 'location': { '$in': locations } }
});
const output = await Users.aggregate(query);
Upvotes: 1