我在 MongoDB 中有一个模型,其中包含一个数组(类别),其中有一个数组(图片)。 衬衫模特看起来像这样:
{ _id: 100, category: [ { name: 'CatName', _id: 101, picture: [Object] } ] }
我的图片数组是这样的:
[ { path: 'p1', _id: 102 },
{ path: 'p2', _id: 103 } ] }
我传递了 3 个变量
- 主数组 ID 为 100 (var1)
- 类别名称是 CatName (var2)
- 图片id为102 (var3)
我想获取一个如下所示的数组:
{ _id: 100, category: [ { name: 'CatName', _id: 101,
picture: [ { path: 'p1', _id: 102 }]
} ]
}
我试过的是这样的:
Shirt.find( {_id: var1} ,
{category: { $and:[ { name: var2 } , { picture: {$elemMatch: {_id: var3}}} ] }} )
.exec(function(err, product) {
console.log('Result ' + product );
res.jsonp(product);
});
但我收到的结果是未定义的第一个代码
我尝试的第二个代码:
Shirt.find( {_id: var1} ,
{category: {$elemMatch: { name: var2,picture: {$elemMatch: {_id: var3} }}} } )
并且第二个代码的结果过滤了 var1 和 var2 的数组 但它包含整个图片数组,这意味着它不会过滤 var3
- 找到我想要的内容的正确代码是什么?
- 这是购物网站数据库的正确方法吗?或者您有更好的建议吗?
- 我是否正确应用父子数据库?
谢谢!
最佳答案
下面的 mongo 查询会给你预期的结果:
db.collection.find({
"category": {
$elemMatch: {
"name": "CatName",
"picture": {
$elemMatch: {
"_id": 102
}
}
}
}
})
需要转成node.js格式
以下格式可能对您有所帮助。 未测试
collection.find({
_id: "" // add your match Id here} ,
{
category: {
"$elemMatch": {
"name": "CatName",
"picture": {
$elemMatch: {
"_id": 102
}
}
}
}
}
})
.exec(function(err, product) {
console.log('Result ' + product);
res.jsonp(product);
});
编辑问题后
你应该使用 mongo aggregation获得所需的值。查询将如下所示 -
db.collection.aggregate({
$unwind: '$category'
}, {
$unwind: '$category.picture'
}, {
$match: {
_id: 100, // add here your var1 variable instead of 100
'category.name': 'CatName', // add here your var2 variable instead of 'CatName'
'category._id': 102, //add your match id here if any otherwise remove this condition
'category.picture._id': 102 //add your var3 instead of 102
}
}, {
$group: {
_id: '$category.name',
'name': {
$first: '$category.name'
},
'picture': {
'$push': '$category.picture'
}
}
})
关于arrays - Node.JS + MongoDB 聚合 从 MongoDB 中的数据库中查找数组中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30567073/