【问题标题】:Aggregate count Values in MongoDbMongoDb 中的聚合计数值
【发布时间】:2020-01-20 07:51:03
【问题描述】:

请,我需要帮助来汇总 MongoDb 嵌套文档中的状态(2 和 3)计数。

我的 Json:

[
   {
      "_id":1,
      "name":"aaa",
      "calendars":[
         {
            "year":2012,
            "status":2
         },
         {
            "year":2013,
            "status":1
         },
         {
            "year":2014,
            "status":3
         }
      ]
   },
   {
      "_id":2,
      "name":"bbb",
      "calendars":[
         {
            "year":2012,
            "status":1
         },
         {
            "year":2013,
            "status":1
         },
         {
            "year":2014,
            "status":2
         }
      ]
   }
]

这是我的 mongodb 代码:

db.mycol.aggregate([{"$match": {"calendars.status": {"$in": [2, 3]}}}, {"$unwind": "$calendars"},
                    {"$group": {_id: {"year": "$calendars.year"},
                                total: {"$sum": 1}
                                }},
                    {"$project": {
                        "year": "$_id.year",
                        "total": "$total", "_id": 0}},
                    ])

我需要结果:

year total  
2012 1
2013 0
2014 2

谢谢

【问题讨论】:

标签: mongodb count aggregate


【解决方案1】:

我将首先展开数组对象并进行相应的匹配,

 db.test.aggregate([
  {
    "$unwind": "$calendars"
  },
  {
    "$match": {
      "calendars.status": {
        "$in": [
          2,
          3
        ]
      }
    }
  },
  {
    "$group": {
      _id: {
        "year": "$calendars.year"
      },
      total: {
        "$sum": 1
      }
    }
  },
  {
    "$project": {
      "year": "$_id.year",
      "total": "$total",
      "_id": 0
    }
  },

])

【讨论】:

  • $unwind 是我计算重复嵌套数组值的关键。无法通过谷歌找到答案,当我写一个重复的问题时,不得不通过建议得到它。希望点赞和评论能帮助它获得更多曝光。
猜你喜欢
  • 1970-01-01
  • 2016-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
相关资源
最近更新 更多