简体   繁体   中英

how can I get field and value from nested array and query them to find doc in mongodb?

I am trying to get field and values from a nested array which is dynamic(List1 and List2 ar dynamic )

let selectionCritea = {
  List1: [ 'mk singh', 'saurav kashsyap' ],
  List2: [
    { labelName: 'Location', values: ['India','America','Japan'] },
    { labelName: 'gender', values: ['male'] }
  ]
}

I want to find doc from db which has properties as "labelname" and values from corresponding "values" array ie gender is male and Location is either India,America or Japan. here is my modelschema:

{ "_id" : "6123e7ahdhdfdj334733",
    "name" : "Mohit Kumar",
    "gender" : "male",
    "Location" : "India",
    },
   { "_id" : "6123e7ahdhdfdj334731",
    "name" : "saurav  Kashyap",
    "gender" : "male",
    "Location" : "Nepal",
    },
   { "_id" : "6123e7ahdhdfdj334720",
    "name" : "Shaline",
    "gender" : "female",
    "Location" : "america",
    },

so I should get only first doc because gender is male and location in from values array. I have tried all my knowledge but couldnot get it

First of all you need to prepare a query in client side,

 let selectionCritea = { List1: [ 'mk singh', 'saurav kashsyap' ], List2: [ { labelName: 'Location', values: ['India','America','Japan'] }, { labelName: 'gender', values: ['male'] } ] } let query = {}; // get regular expression query condition let names = []; selectionCritea.List1.forEach(q => { names.push(q) }) if(names.length) { query.name = { $regex: names.join("|") } } // prepare List2 conditions selectionCritea.List2.forEach(q => { query[q.labelName] = (Array.isArray(q.values)? { $in: q.values }: q.values); }) console.log(query)

You can use the above prepared query in find query:

db.collection.find(query);

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM