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 Group by field, count it with condition

I would like to count different hu for a shipment. So I write this query but how I can count different hu group by shipment ?

my query :

db.eventstranslated.aggregate([
  { "$group": {
    "_id": "$IdShipment",
    "count": { "$sum": 1 }
  }},
  { "$group": {
    "_id": null,
    "ship": {
      "$push": {
        "shipment": "$_id",
        "count": "$count"
      }
    }
  }},
  { "$project": { "_id": 0 }}
])

Result :

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

{ shipment: A01, count: 1 },
{ shipment: A02, count: 1 },

expect output:

{shipment: A01, count: 2 }
{shipment: A02, count: 1 }

my collection:

{
  _id: 1,
  IdShipment: "A01",
  hu: "C111"
},
{
  _id: 2,
  IdShipment: "A01",
  hu: "C112"
},
{
  _id: 3,
  IdShipment: "A02",
  hu: "D111"
},
{
  _id: 4,
  IdShipment: "A02",
  hu: "D111"
}

>Solution :

You can use two $group stages like this:

First $group has a compound key to get all differents options, and the second $group is to get only differents IdShipment.

db.collection.aggregate([
  {
    "$group": {
      "_id": {
        "IdShipment": "$IdShipment",
        "hu": "$hu"
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.IdShipment",
      "count": {
        "$sum": 1
      }
    }
  }
])

Example here

Also you can use $project to output the name you want. Example here

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