Thilina Sandaruwan
Thilina Sandaruwan

Reputation: 335

How to find documents which are contains one or more elements of the search array in MongoDB?

I have a database in MongoDB, Here is sample collection of it.

[
  {
    id:123,
    name: "name1",
    likes: ["swim","run","walk"]
  },
  {
    id:123,
    name: "name1",
    likes: ["swim","hike","run"]
  },
  {
    id:123,
    name: "name1",
    likes: ["talk","run","sing"]
  }
]

Then I have another array contains the search keywords

["hike","talk"]

So I need result like this.

  {
    id:123,
    name: "name1",
    likes: ["swim","hike","run"]
  },
  {
    id:123,
    name: "name1",
    likes: ["talk","run","sing"]
  }

Help me to solve this. I use mongoose ODM and express.js

Upvotes: 0

Views: 120

Answers (2)

Abhineet
Abhineet

Reputation: 60

You can use $or operator to see if any one of multiple queries in array is true. So for above code, you can query like:

db.collection.find({$or:[{likes:"hike"},{likes:"talk"}]})

Which says find all the entries in our db which satisfy that either of the conditions (hike exist in our like array or talk exists in our like array) is satisfied.

Upvotes: 1

vishnu
vishnu

Reputation: 2011

You can use the $in operator. documentation

MyModel.find({likes : {$in : ['hike', 'talk']}}, (err, data) => {
  if (err) {
    console.log(err);
  } else {
    console.log(data);
  }
});

Upvotes: 1

Related Questions