0

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.

0

1 Answer 1

1

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"
        ]
      }
    }
  }
])

MongoPlayground

EDIT: Nodejs code

let query     = [];
let locations = ['pune', 'nashik'];
query.push({
    '$match': { 'location': { '$in': locations } }                
});
const output = await Users.aggregate(query);
Sign up to request clarification or add additional context in comments.

1 Comment

it works fine. but when I do the same thing with aggregate query it gives MongoError: $in needs an array Error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.