【发布时间】:2015-11-16 07:29:53
【问题描述】:
这是我的 MongoDB 集合架构:
company: String
model: String
cons: [String] // array of tags that were marked as "cons"
pros: [String] // array of tags that were marked as "pros"
我需要聚合它,以便得到以下输出:
[{
"_id": {
"company": "Lenovo",
"model": "T400"
},
"tags": {
tag: "SomeTag"
pros: 124 // number of times, "SomeTag" tag was found in "pros" array in `Lenovo T400`
cons: 345 // number of times, "SomeTag" tag was found in "cons" array in `Lenovo T400`
}
}...]
我尝试执行以下操作:
var aggParams = {};
aggParams.push({ $unwind: '$cons' });
aggParams.push({ $unwind: '$pros' });
aggParams.push({$group: {
_id: {
company: '$company',
model: '$model',
consTag: '$cons'
},
consTagCount: { $sum: 1 }
}});
aggParams.push({$group: {
_id: {
company: '$_id.company',
model: '$_id.model',
prosTag: '$pros'
},
prosTagCount: { $sum: 1 }
}});
aggParams.push({$group: {
_id: {
company:'$_id.company',
model: '$_id.model'
},
tags: { $push: { tag: { $or: ['$_id.consTag', '$_id.prosTag'] }, cons: '$consTagCount', pros: '$prosTagCount'} }
}});
但我得到了以下结果:
{
"_id": {
"company": "Lenovo",
"model": "T400"
},
"tags": [
{
"tag": false,
"pros": 7
}
]
}
使用aggregation 的正确方法是什么?
【问题讨论】:
-
我们可以在这里假设“pros”或“cons”中的“tag”在任一数组中都是唯一的,或者实际上在两个数组中都是“唯一的”?当然是每个文件。
-
正确,每个文档的标签都是唯一的(两个数组中的“唯一”)
-
所以要完全清楚。 “SomeTag”只会在每个文档中出现一次,比如“pros”而不是“cons”?
-
@BlakesSeven 不,一个标签可能同时出现在“pros”和“cons”中
-
两者都能出现就可以了。这里的关键元素是它永远不会多次出现在“专业人士”中。
标签: node.js mongodb mongoose mongodb-query aggregation-framework