Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading