Home > Enterprise >  Dynamically query a nested field in mongoDb
Dynamically query a nested field in mongoDb

Time:11-09

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',
];
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

                const query = {
                    visibility: true,
                    $or: [
                        {"myField.sample1": true},
                        {"myField.sample2": true},
                    ]
                };
                const recipes = await Recipe.find(query).countDocuments();
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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?

CodePudding user response:

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)
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related