I've got a collection like this:
{
"_id": ObjectID(1),
"fruits": [Banana, Banana, Apple]
}
{
"_id": ObjectID(2),
"fruits": [Apple]
}
I want to get the count of the array data, like 2 Banana and 1 Apple for the first object; 1 Apple for the second object.
How can i do this?
CodePudding user response:
$unwind
- Deconstructfruits
array into multiple documents.$group
- Group by_id
andfruits
. Perform count.$group
- Group by_id._id
. Push object intofruits
array.$set
- Setfruits
to key-value pair.
db.collection.aggregate([
{
$unwind: "$fruits"
},
{
$group: {
_id: {
_id: "$_id",
fruit: "$fruits"
},
count: {
$sum: 1
}
}
},
{
$group: {
_id: "$_id._id",
fruits: {
$push: {
k: "$_id.fruit",
v: "$count"
}
}
}
},
{
$set: {
fruits: {
$arrayToObject: "$fruits"
}
}
}
])
Output
[
{
"_id": 2,
"fruits": {
"Apple": 1
}
},
{
"_id": 1,
"fruits": {
"Apple": 1,
"Banana": 2
}
}
]