简体   繁体   English

MongoDb 中的聚合计数值

[英]Aggregate count Values in MongoDb

Please, I need a help for aggregate the status (2 and 3) count from year in a MongoDb nested document.拜托,我需要帮助来汇总 MongoDb 嵌套文档中年份的状态(2 和 3)计数。

My 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
         }
      ]
   }
]

This is my mongodb code:这是我的 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}},
                    ])

And I need the result:我需要结果:

year total  
2012 1
2013 0
2014 2

Thanks谢谢

I will first unwind the array object and match accordingly,我将首先展开数组对象并进行相应的匹配,

 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
    }
  },

])

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

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