Given: A single document in collection. The Document contains an array. (i.e. Only one document entry exist in Collection)
Expectation :
perform group by on city and print counts
Sample Data:
{
name: "ABC Bank",
hospitalList: [
{city: "Delhi", hspName: "EEE hospital"},
{city: "Delhi", hspName: "FFF hospital"},
{city: "Surat", hspName: "MMM hospital"},
{city: "Noida", hspName: "GGG hospital"},
{city: "Surat", hspName: "HHH hospital"},
{city: "Surat", hspName: "NNN hospital"},
{city: "Surat", hspName: "PPP hospital"},
]
}
Expected Output:
Delhi - 2
Noida - 1
Surat - 3
Tried (but did NOT work)
$group: {
_id: "hospitalList.city",
count: { $sum: 1 }
}
db.collection.aggregate([
{
$match: {
name: "ABC Bank"
}
},
{
"$unwind": "$hospitalList"
},
{
$group: {
_id: "$hospitalList.city",
count: {
$sum: 1
}
}
}
])
Mongo playground: https://mongoplayground.net/p/Ac7RkJd7vU9
as per expected output: Mongo playground: https://mongoplayground.net/p/zeqB7P-BYmI