Home > Back-end >  Count the documents and sum of values of fields in all documents of a mongodb
Count the documents and sum of values of fields in all documents of a mongodb

Time:08-08

I have a set of documents modified from mongodb using

[{"$project":{"pred":1, "base-url":1}},
                  {"$group":{
                      "_id":"$base-url",
                      "invalid":{"$sum": { "$cond": [{ "$eq": ["$pred", "invalid"] }, 1, 0] }},
                      "pending":{"$sum": { "$cond": [{ "$eq": ["$pred", "null"] }, 1, 0] }},
                  }},
                ]

to get the below documents

[{'_id': 'https://www.example1.org/', 'invalid': 3, 'pending': 6},
 {'_id': 'https://example2.com/', 'invalid': 10, 'pending': 4},
 {'_id': 'https://www.example3.org/', 'invalid': 2, 'pending': 6}]

How to get the count of documents and sum of other fields to obtain the following result

{"count":3, "invalid":15,"pending":16}

CodePudding user response:

you just need a $group stage with $sum
playground

The $sum docs and here has good examples

db.collection.aggregate([
  {
    $group: {
      _id: null,
      pending: {
        $sum: "$pending"
      },
      invalid: {
        $sum: "$invalid"
      },
      count: {
        $sum: 1       //counting each record
      }
    }
  },
  {
    $project: {
      _id: 0         //removing _id field from the final output
    }
  }
])
  • Related