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

Mongo Aggregate by multiple props

I need to generate stats from users collection in Mongodb.

USER schema:

{
  _id: ObjectId,
  name: string,
  city: string,
  gender: enunm["Male", "Female"],
}

STATS schema:

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

[
  {
    city: string,
    Male: number, (number of males in that $city)
    Female: number, (number of females in that $city)
  }
]

What aggregation pipeline I should use?

I tried something like this:

db.testCollection.aggregate([
  { $group: { _id: "$status", totalQuantity: { $count: "$stats" } } },
]);

>Solution :

You want to be using $cond to sum conditionally on gender value while grouping, like so:

db.collection.aggregate([
  {
    $group: {
      _id: "$city",
      Male: {
        $sum: {
          $cond: [
            {
              $eq: [
                "$gender",
                "Male"
              ]
            },
            1,
            0
          ]
        }
      },
      Female: {
        $sum: {
          $cond: [
            {
              $eq: [
                "$gender",
                "Female"
              ]
            },
            1,
            0
          ]
        }
      }
    }
  },
  {
    $project: {
      Female: 1,
      Male: 1,
      city: "$_id",
      _id: 0
    }
  }
])

Mongo Playground

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