我正试图从一个动态嵌套数组中获取字段和值(List1和List2是动态的)
let selectionCritea = {
List1: [ 'mk singh', 'saurav kashsyap' ],
List2: [
{ labelName: 'Location', values: ['India','America','Japan'] },
{ labelName: 'gender', values: ['male'] }
]
}
我想找到文档从db有属性为"labelname"并从相应的"值"中获取值数组即性别是男性,地点是印度、美国或日本。下面是我的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",
},
所以我应该只得到第一个文档,因为性别是男性和位置在从值数组。我已经试了所有的知识,但还是没有成功。
首先需要在客户端准备一个查询,
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)
您可以在find query:
中使用上述准备好的查询db.collection.find(query);
游乐场