Search code examples
mongodbaggregate

MongoDB needs to get total counts from all objects


my aggregate query looks like this. I need to get the total count from the value.

db.getCollection('mydesk').aggregate([
{
    $match: {
        "accountId": ObjectId("616ea615edc5fa4278ccb7f6"),
                "val" : { $ne : null},
        "deskId": { "$in": [ 
                ObjectId("61934f7efdb9dc5a7c1c3a01"), 
                ObjectId("61713730857c3243ec1d257c"), 
                ObjectId("629d9548e0c93e34e435e7b9"), 
                ObjectId("616eaf613bcd9655b8035a25"), 
            ]}
    }
},
{
      $project: {
         item: 1,
         value:  { $size: "$val.shapes" },
      }
}

])

I got result like this. But need to get the total counts of my value.

/* 1 */
{
    "_id" : ObjectId("616fab4f12b90d59d03f380e"),
    "value" : 11
}

/* 2 */
{
    "_id" : ObjectId("616fbad35700980a041cd190"),
    "value" : 4
}

/* 3 */
{
    "_id" : ObjectId("61713752857c3243ec1d257e"),
    "value" : 12
}

Needed result :

{
    "totalValueCount" : 27
}

Thanks in advance


Solution

  • One option is to use $group to $sum up the values:

    db.getCollection('mydesk').aggregate([
      {
        $match: {
            "accountId": ObjectId("616ea615edc5fa4278ccb7f6"),
            "val" : { $ne : null},
            "deskId": { "$in": [ 
                    ObjectId("61934f7efdb9dc5a7c1c3a01"), 
                    ObjectId("61713730857c3243ec1d257c"), 
                    ObjectId("629d9548e0c93e34e435e7b9"), 
                    ObjectId("616eaf613bcd9655b8035a25"), 
                ]}
        }
      },
      {
          $group: {
             _id: null,
             total:  {$sum: { $size: "$val.shapes"}},
          }
      },
      {$project: {_id: 0, total: 1}}
    
    ])