如何从嵌套数组中获取字段和值并查询它们以在 mongodb 中查找文档?

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

我正在尝试从动态嵌套数组(List1 和 List2 ar 动态)中获取字段和值

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

我想从 db 中查找具有“labelname”属性和相应“values”数组中的值的文档 即性别是男性,位置是印度、美国或日本。 这是我的模型架构:

{ "_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)

您可以在查找查询中使用上面准备好的查询:

db.collection.find(query);

Playground