这是我的 MongoDB 集合架构:
company: String
model: String
tags: [String]
我需要聚合它,以便得到以下输出:
[{
"_id": {
"company": "Lenovo",
"model": "T400"
},
"tags": {
tag: "SomeTag"
count: 124 // number of times, this tag was found in `Lenovo T400`
}
}...]
我尝试执行以下操作:
var aggParams = {};
aggParams.push({ $unwind: '$tags' });
aggParams.push({ $group: {
_id: { company: '$company', model: '$model' },
tags: { $push: { tag: '$tags', count: { $sum: 1 } } },
}});
但我收到以下错误:
invalid operator '$sum'
执行此操作的正确方法是什么aggregation
?
你需要处理$unwind http://docs.mongodb.org/manual/reference/operator/aggregation/unwind/在数组上以便在聚合中有意义地处理它。此外,您还可以添加到数组并“计数”单独的阶段。以及参数本身“数组”中的聚合管道,而不是您定义的对象:
Model.aggregate([
{ "$unwind": "$tags" },
{ "$group": {
"_id": {
"company": "$company",
"model": "$model",
"tag": "$tags"
},
"count": { "$sum": 1 }
}},
{ "$group": {
"_id": {
"company": "$_id.company",
"model": "$_id.model",
},
"tags": { "$push": { "tag": "$_id.tag", "count": "$count" }
}}
], function(err,result) {
})
So two $group http://docs.mongodb.org/manual/reference/operator/aggregation/group/stage 在这里完成工作。一个用于汇总公司和型号内的标签,另一个用于仅对“公司”和“型号”进行分组,并将不同的标签和计数添加到数组中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)