简体   繁体   English

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

[英]MongoDB aggregate count of items in array across different documents?

Here is my MongoDB collection schema: 这是我的MongoDB集合架构:

company: String
model: String
tags: [String]

I need to aggregate it so I get the following output: 我需要对其进行汇总,以得到以下输出:

[{
  "_id": {
    "company": "Lenovo",
    "model": "T400"
  },
  "tags": {
    tag: "SomeTag"
    count: 124 // number of times, this tag was found in `Lenovo T400`
  }
}...]

I tried to do the following: 我尝试执行以下操作:

var aggParams = {};
aggParams.push({ $unwind: '$tags' });
aggParams.push({ $group: {
  _id: { company: '$company', model: '$model'  },
  tags: { $push:  { tag: '$tags', count: { $sum: 1 } } },
}});

But I got the following error: 但我收到以下错误:

invalid operator '$sum'

What is the right way to do this with aggregation ? aggregation执行此操作的正确方法是什么?

You need to process $unwind on an array in order to deal with it meaninfully in aggregation. 您需要在数组上处理$unwind才能有意义地进行聚合处理。 Also you adding to an array and "counts" stage a separate. 同样,您将添加到数组中并“计数”一个阶段。 As well an aggregation pipeline in an "array" of arguments itself, and not an object as you have defined: 同样,参数本身的“数组”中的聚合管道也并非您定义的对象:

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 stages does the job here. 因此,两个$group阶段在这里完成了工作。 One to sum up the tags within company and model and the other to group on just the "company" and "model" and add the distinct tags and counts to an array. 一个用于汇总公司和模型中的标签,另一个用于仅对“公司”和“模型”进行分组,并将不同的标签和计数添加到数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM