Categories
JavaScript Answers

How to combine two OR-queries with AND in Mongoose and JavaScript?

Spread the love

To combine two OR-queries with AND in Mongoose and JavaScript, we use $and and $or together.

For instance, we write

Test.find(
  {
    $and: [{ $or: [{ a: 1 }, { b: 1 }] }, { $or: [{ c: 1 }, { d: 1 }] }],
  },
  (err, results) => {
    //...
  }
);

to call find with an object with the $and property set to an array with 2 objects with $or properties.

The 2 $or queries will then be combined with the $and query.

We get the returned results from results.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *