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: Count by unique value after aggregate by group

I have get count unique value by group
Here is the example data

[
   {
     iphone: iphone6,
     name: Tom
   },
   {
     iphone:iphone7,
     name: Tom
   },
   {
     iphone:iphone6,
     name: Joe
   },
   {
     iphone:iphoneX,
     name: Joe
   }
]

I want to group by showing like:

[
   {
     _id:iphone6,
     people:[Tom,Joe]
   },
   {
     _id:iphone7,
     people:[Tom]
   },
   {
     _id:iphoneX,
     people:[Joe]
   }
]

I have a problem with using $group. How can I do this?

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

>Solution :

  1. $group: Group by iphone and $push name to people array field.
  2. $sort (Optional): Sort by _id ascending.
db.collection.aggregate([
  {
    $group: {
      _id: "$iphone",
      people: {
        $push: "$name"
      }
    }
  },
  {
    $sort: {
      _id: 1
    }
  }
])

Sample 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