Home > database >  MongoDB pipeline conditional counting
MongoDB pipeline conditional counting

Time:12-24

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
                    ]
                }
            }
        }
    }
]

CodePudding user response:

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.

  • Related