Andre Vieira de Lima
Andre Vieira de Lima

Reputation: 65

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.

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:

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

Upvotes: 0

Views: 72

Answers (1)

Sohan
Sohan

Reputation: 6809

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

])

Upvotes: 4

Related Questions