MongoDB汇总不同文档中数组中的项目总数? [英] MongoDB aggregate count of items in array across different documents?

查看:49
本文介绍了MongoDB汇总不同文档中数组中的项目总数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的MongoDB收集模式:

Here is my MongoDB collection schema:

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`
  }
}...]

我尝试执行以下操作:

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'

aggregation执行此操作的正确方法是什么?

What is the right way to do this with aggregation?

推荐答案

您需要处理 $unwind 以便在聚合中有意义地处理它.另外,您要添加到数组中并计数"一个单独的阶段.以及参数本身的数组"中的聚合管道,而不是您定义的对象:

You need to process $unwind on an array in order to deal with it meaninfully in aggregation. 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) {

})

所以有两个 $group 阶段在这里完成工作.一种是对公司和模型中的标签进行汇总,另一种是仅对公司"和模型"进行分组,然后将不同的标签和计数添加到数组中.

So two $group stages does the job here. 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.

这篇关于MongoDB汇总不同文档中数组中的项目总数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆