我正在尝试根据URL发送的输入查询参数数组从mongodb集合中查询文档。
样本数据库数据
[
{
"drawings": {
"circle": [],
"square": [
{
"id": "828",
"name": "square"
}
],
"cube": []
},
{
"drawings": {
"circle": [
{
"id": "827",
"name": "circle"
}
],
"square": [],
"cube": []
},
{
"drawings": {
"circle": [],
"square": [],
"cube": [
{
"id": "829",
"name": "cube"
}
]
}
]
输入查询参数:
query = ["square","cube"];
预期输出:
[
{
"drawings": {
"circle": [],
"square": [
{
"id": "828",
"name": "square"
}
],
"cube": []
},
{
"drawings": {
"circle": [],
"square": [],
"cube": [
{
"id": "829",
"name": "cube"
}
]
}
]
最合适的猫鼬查询:
Schema.find({
$or:[
{'drawings.square':{$elemMatch:{ name:'square'}}},
{'drawings.cube':{$elemMatch:{ name:'cube'}}}
]
});
尝试以下方法。但是,这是不正确的。
let draw = ["square","cube"];
let draw_query =[];
for (let a=0; a<draw.length;a++){
draw_query.push("{\"drawings."+ draw[a] +"\':{$elemMatch:{ name:\"" + draw[a] + "\"}}}");
}
它使用单引号字符串创建数组。无法使用。
[ '{"drawings.square":{$elemMatch:{ name:"square"}}}',
'{"drawings.cube":{$elemMatch:{ name:"cube"}}}' ]
如何动态生成此猫鼬查询?还是有更好的猫鼬查询来达到预期的结果。
答案 0 :(得分:1)
您可以直接使用点符号查询它,因此查询应如下所示:
db.collection.find({
$or: [
{
"drawings.square.name": "square"
},
{
"drawings.circle.name": "circle"
}
]
})
您可以使用.map()
在JS中进行构建,请尝试:
var query = ["square","cube"];
var orQuery = { $or: query.map(x => ({ [x + ".name"]: x }) ) }