0

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?

0

1 Answer 1

3

Use below aggregation. You are missing a $match stage after $unwind.

Initial match only filters document where there exists fruits array with at least one fruit from matching input fruits array.

Once you $unwind it unwinds all the fruits which also includes other fruits. So when you use second match you filter the fruits to only contain fruits matching from input fruits array.

db.fruits.aggregate([
  {"$match":{"state":"Karnataka","fruits":{"$elemMatch":{"$in":["banana","coconut"]}}}},
  {"$unwind":"$fruits"},
  {"$match":{"fruits":{"$in":["banana","coconut"]}}},
  {"$group":{"_id":"$fruits","count":{"$sum":1}}}
])
Sign up to request clarification or add additional context in comments.

6 Comments

Will you please help me with this. I want a counts of fruits containing banana, coconunt, [banana, coconut](no $elementMatch i.e $all) separately
Not sure I follow you. You want count of all fruits together ?
No no. I want to query array of array.. like ["banana, coconut, lemon"] , ["orange", "jackfruit"] returning array with counts opposite to $elementMatch
I see. You can write a or condition with each condition being in criteria matching each array. Something like {$or:[{$in:first set}, repeat for all sets]}
But Using $or will give me count for only one array condition. I want it for all at once like above output.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.