Home > Mobile >  MongoDB: Count by unique value after aggregate by group
MongoDB: Count by unique value after aggregate by group

Time:11-25

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?

CodePudding user response:

  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

  • Related