【发布时间】:2015-05-22 06:16:29
【问题描述】:
我有一个名为“商店”的集合。结构如下:
[
{
'_id' : id1,
'details' : {name: 'shopA'},
'products' : [{
_id: 'p1',
details: {
'name': 'product1'
}
},{
_id: 'p2',
details: {
'name': 'product2'
}
}, {
_id: 'p4',
details: {
'name': 'product4'
}
}
},{
'_id' : id2,
'details' : {name: 'shopB'},
'products' : [{
_id: 'p1',
details: {
'name': 'product1'
}
},{
_id: 'p4',
details: {
'name': 'product4'
}
}, {
_id: 'p5',
details: {
'name': 'product5'
}
}
},{
'_id' : id3,
'details' : {name: 'shopC'},
'products' : [{
_id: 'p1',
details: {
'name': 'product1'
}
},{
_id: 'p2',
details: {
'name': 'product2'
}
}, {
_id: 'p3',
details: {
'name': 'product3'
}
}
},{
'_id' : id4,
'details' : {name: 'shopOther'},
'products' : [{
_id: 'p10',
details: {
'name': 'product10'
}
},{
_id: 'p12',
details: {
'name': 'product12'
}
}, {
_id: 'p13',
details: {
'name': 'product13'
}
}
}
]
现在用户可以从菜单中选择一些产品并尝试为这些产品找到商店。结果应该是提供至少一种选定商品的所有商店。
例子,
假设用户选择['p1', 'p2', 'p3'] //ids
然后只有三个商店
id1, id2, id3 将被列出(id4 没有这些项目),加上结构使得它从结果数组中的文档中删除商店的其余产品(未列出)。
有没有办法,我可以直接从 mongodb 得到这样的结果?
【问题讨论】:
-
查看答案列表
.aggregate(),也可能在this question的回复下方查看$redact -
好的,我会检查的
-
$redact 应该适用于剥离结果,但我如何只搜索那些在查询列表中至少包含一个元素的文档?
-
查看文档$match 用于一般查询,$in 运算符用于查询选择以及dot notation。特别是
{ "$match": { "products._id": { "$in": ["p1","p2","p3"] } }}。有关聚合管道的进一步阅读也在核心文档中。以及这里的许多示例aggregation-framework -
我认为这是我的工作。谢谢。
标签: javascript node.js mongodb aggregation-framework mongoskin