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:
$group
: Group byiphone
and$push
name
topeople
array field.$sort
(Optional): Sort by_id
ascending.
db.collection.aggregate([
{
$group: {
_id: "$iphone",
people: {
$push: "$name"
}
}
},
{
$sort: {
_id: 1
}
}
])