【问题标题】:MongoDB aggregate count of items in array across different documents?MongoDB在不同文档中汇总数组中的项目数?
【发布时间】:2015-11-16 06:29:27
【问题描述】:

这是我的 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 的正确方法是什么?

【问题讨论】:

  • 您的数据与您的架构相矛盾。您的实际数据中的“标签”是什么?一个字符串?还是数组?
  • [String] - 代表一个字符串数组

标签: javascript mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

您需要在数组上处理$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) {

})

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

【讨论】:

    猜你喜欢
    • 2015-11-16
    • 2015-11-16
    • 2020-06-26
    • 2018-06-06
    • 1970-01-01
    • 2017-11-19
    • 2023-03-05
    • 1970-01-01
    • 2020-07-17
    相关资源
    最近更新 更多