MongoDB 不同文档中数组中项目的总计数?

MongoDB aggregate count of items in array across different documents?

这是我的 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 以便在聚合中有意义地处理它。另外,您将添加到一个数组并 "counts" 单独分阶段。以及 "array" 参数本身中的聚合管道,而不是您定义的对象:

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) {

})

所以两个 $group 阶段完成这里的工作。一个总结公司和模型中的标签,另一个仅对 "company" 和 "model" 进行分组,并将不同的标签和计数添加到数组中。