To GROUP BY array of the document, use $group. Let us create a collection with documents −
>db.demo559.insertOne({details:[{Name:"Chris",Age:21},{Name:"Bob",Age:22},{Name:"Carol", Age:21},{Name:"Sam",Age:21}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e8f38d954b4472ed3e8e866")
}Display all documents from a collection with the help of find() method −
> db.demo559.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e8f38d954b4472ed3e8e866"),
"details" : [
{
"Name" : "Chris",
"Age" : 21
},
{
"Name" : "Bob",
"Age" : 22
},
{
"Name" : "Carol",
"Age" : 21
},
{
"Name" : "Sam",
"Age" : 21
}
]
}Following is the query to group by an array of the document −
> db.demo559.aggregate([
... {
... "$unwind": "$details"
... },
... {
... "$group": {
... "_id": "$details.Age",
... "Count": { "$sum" : 1 }
... }
... },
... { "$sort": { "_id" : 1 } }
... ])This will produce the following output −
{ "_id" : 21, "Count" : 3 }
{ "_id" : 22, "Count" : 1 }