It'sNotMe
It'sNotMe

Reputation: 1260

MongoDB pipeline conditional counting

Documents in a collection contain title and active fields. The active field is boolean. My goal is to group by title and count all the records. Lastly, I want to count the documents where active is true.

This query does the counting, but total and active are always equal. Why isn't the conditional counting only the documents where active is true?

Here is my pipeline:

[
    { 
        "$group" : { 
            "_id" : { 
                "student᎐campus᎐title" : "$student.campus.title"
            }, 
            "total" : { 
                "$sum" : NumberInt(1)
            }, 
            "active" : { 
                "$sum" : { 
                    "$cond" : [
                        { 
                            "active" : true
                        }, 
                        1.0, 
                        0.0
                    ]
                }
            }
        }
    }
]

Upvotes: 0

Views: 51

Answers (1)

ray
ray

Reputation: 15217

Your code doesn't work because you are evaluating expression objects instead of operator expressions

Try below working version:

db.collection.aggregate([
  {
    "$group": {
      "_id": "$title",
      "total": {
        "$sum": 1
      },
      "active": {
        "$sum": {
          "$cond": [
            "$active",
            1.0,
            0.0
          ]
        }
      }
    }
  }
])

Here is the Mongo playground for your reference.


EDIT: thanks to @wernfriedDomscheit 's advice, here is a more concise version using $toInt for MongoDB v4.0+

db.collection.aggregate([
  {
    "$group": {
      "_id": "$title",
      "total": {
        "$sum": 1
      },
      "active": {
        "$sum": {
          "$toInt": "$active"
        }
      }
    }
  }
])

Mongo playground

Upvotes: 1

Related Questions