My data:
{
"_id" : ObjectId("542911f4d7054ab6ee0de476"),
"name" : "policy2",
"url" : [ "www.url22.com", "www.url21.com" ],
"countries" : [
{ "country" : "USA" },
{ "country" : "GER" }
]
}
I would like to count the occurrence of USA and China separately for the group by countries.country field, instead of [USA,GER] appearing together several times, as follows:
{ "_id" : "China", "total" : 1 }
{ "_id" : "USA", "total" : 2 }
{ "_id" : "GER", "total" : 1 }
{ "_id" : "JP", "total" : 1 }
I tried to use aggregate
db.policy.aggregate({$group:{_id:"$countries.country",total:{$sum:1}}})
But the result is the statistical result of countries:
{ "_id" : [ "China" ], "total" : 1 }
{ "_id" : [ "USA", "JP" ], "total" : 1 }
{ "_id" : [ "USA", "GER" ], "total" : 1 }
Seek a solution! !
Use$unwind:
db.policy.aggregate([ { $unwind: '$countries' }, { $group: { _id: '$countries.country', total: { $sum: 1 } } } ]);