My collection has following format -
{
"title" : "Seasonal",
"state" : "Maharashtra",
"fruits" : [ "banana", "orange", "jackfruit", "mango", "tamarind"]
}
{
"title" : "Seasonal",
"state" : "Karnataka",
"fruits" : [ "banana", "avacado", "blackberry", "coconut", "grape"]
}
{
"title" : "Alltime",
"state" : "Karnataka",
"fruits" : [ "banana", "lemon", "pomegranate", "pineapple"]
}
And my query is like
db.fruits.aggregate([{"$match": {"state": "Karnataka", "fruits": {"$elemMatch": {"$in": ["banana","coconut"]}}}},{ $unwind : "$fruits" },{"$group" : {"_id" : "$fruits","count" : {"$sum":1}}}])
And getting Output as -
{ "_id" : "pineapple", "count" : 1 }
{ "_id" : "lemon", "count" : 1 }
{ "_id" : "grape", "count" : 1 }
{ "_id" : "pomegranate", "count" : 1 }
{ "_id" : "coconut", "count" : 1 }
{ "_id" : "blackberry", "count" : 1 }
{ "_id" : "avacado", "count" : 1 }
{ "_id" : "banana", "count" : 2 }
Instead in return what I want is input fruit names with count of their occurance. i.e.
{ "_id" : "coconut", "count" : 1 }
{ "_id" : "banana", "count" : 2 }
Will you please tell me, How to $group these array elements?