Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
How to dynamically nest $or operator into $and Mongoose statement?

Suppose I have 3 MongDB entries in a movie database:

"books": [
  {
    "_id": "xxxxxx",
    "title": "Fast Five",
    "rating": 6
  },
  {
    "_id": "yyyyyy",
    "title": "Kill Bill",
    "rating": 8
  },
  {
    "_id": "zzzzzzzz",
    "title": "Jumanji",
    "rating": 5
  }
]

I use GraphQL to retrieve the id of multiple movies if their title and rating match the criteria:

query{
   getMovies(itemFilterInput: {titles:["Fast Five", "Jumanji"], rating:6}){
    _id
   title
  }
}

This should return Fast Five. I want this to translate into a mongoDB query like this:

{$and: [{rating:6}, {$or: [{title:"Fast Five", title:"Jumanji"}]}]}

In the backend, I use NodeJS and Mongoose to handle this query and I use something like this:

 getMovies: async args => {
try{
  let d = args.itemFilterInput;
  let filters = new Array();

  const keys = Object.keys(d);
  keys.forEach((key) => {
      // The titles case
      if(d[key] instanceof Array){
        var sObj = {};
        var sObjArray = [];
        d[key].map(prop => {
          sObj[key] = prop;
          sObjArray.push(sObj);
        });
        filters.push({$or: sObjArray});
      }else{
        // The rating case
        var obj = {};
        obj[key] = d[key];
        filters.push(obj);
      }
  });

  const items = await Item.find({$and: filters});
  return items.map(item => {
    return item;
  });
} catch (err) {
  throw err;
}

}

Unfortunately, this approach does not work. What is the correct way to nest $or parameters in $and params?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Answer:

First of all, it is better to use the $in operator instead of a $and/$or combination.

And to solve the error: use quotes everywhere to declare the query.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!