Reputation: 3
I have to get count unique values 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?
Upvotes: 0
Views: 585
Reputation: 51125
$group
: Group by iphone
and $push
name
to people
array field.$sort
(Optional): Sort by _id
ascending.db.collection.aggregate([
{
$group: {
_id: "$iphone",
people: {
$push: "$name"
}
}
},
{
$sort: {
_id: 1
}
}
])
Upvotes: 2