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

179
Views
Dynamically query a nested field in mongoDb

I want to make a query to my mongoDb with this query. I however have a challenge in making a dynamic query.

Here is a sample array for a user. The problem is that the preferences are different for each user.

dynamicArray = [
  'sample1',
  'sample2',
];

                const query = {
                    visibility: true,
                    $or: [
                        {"myField.sample1": true},
                        {"myField.sample2": true},
                    ]
                };
                const recipes = await Recipe.find(query).countDocuments();

This works because I hardcoded the values of sample1 and sample2 from the array. I need to be able to pass sample1, and sample2 dynamically into the query based on the values in the dynamicArray without hard coding them like I did here. How can I get this done please?

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

0

You can use this script to generate objects into the array.

const dynamicArray = [
  'sample1',
  'sample2',
];

var query = {visibility: true,
             $or: []};
             
dynamicArray.map(m => {
    const key = "myField."+m
    var obj = {}
    obj[key] = true
    query.$or.push(obj)})
console.log(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!