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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)