Home > Enterprise >  How to count documents with condition in aggregation's $group (distinct) in my case?
How to count documents with condition in aggregation's $group (distinct) in my case?

Time:08-28

This is sandbox.

Right now i get this output:

[
  {
    "_id": [
      1,
      2
    ],
    "created_at": NumberLong(1661152555),
    "target": 1,
    "text": "5",
    "user": 2,
    "viewed": false
  },
  {
    "_id": [
      1,
      5
    ],
    "created_at": NumberLong(1661152450),
    "target": 1,
    "text": "4",
    "user": 5,
    "viewed": false
  }
]

But i would want to get this:

[
  {
    "_id": [
      1,
      2
    ],
    "created_at": NumberLong(1661152555),
    "target": 1,
    "text": "5",
    "user": 2,
    "viewed": false,
    "newField": 1
  },
  {
    "_id": [
      1,
      5
    ],
    "created_at": NumberLong(1661152450),
    "target": 1,
    "text": "4",
    "user": 5,
    "viewed": false,
    "newField": 2
  }
]

Where newField means quantity of messages with viewed: false for each returned distinct value by roommates: [1, x]. And as you can see i limit returned values to 25 maximum. But of course i need count it within all collection. How can i accomplish it?

CodePudding user response:

In $group stage, using $sum operator with $cond operator.

{
  "$group": {
    ...,
    newField: {
      $sum: {
        $cond: {
          if: {
            $eq: [
              "$viewed",
              false
            ]
          },
          then: 1,
          else: 0
        }
      }
    }
  }
}

Demo @ Mongo Playground

  • Related