How to access overall document count during arithmetic aggregation expression

One way to do it is use $setWindowFields:

db.collection.aggregate([
  {
    $setWindowFields: {
      output: {
        totalCount: {$count: {}}
      }
    }
  },
  {
    $unwind: "$items"
  },
  {
    $group: {
      _id: "$items.defindex",
      count: {$sum: 1},
      totalCount: {$first: "$totalCount"}
    }
  },
  {
    $project: {
      count: 1,
      usage: {$divide: ["$count", "$totalCount"]
      }
    }
  },
  {$sort: {count: -1}}
])

As you can see here

Leave a Comment