我的收藏品有以下格式 -
{
"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"]
}
我的查询就像
db.fruits.aggregate([{"$match": {"state": "Karnataka", "fruits": {"$elemMatch": {"$in": ["banana","coconut"]}}}},{ $unwind : "$fruits" },{"$group" : {"_id" : "$fruits","count" : {"$sum":1}}}])
将输出设为 -
{ "_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 }
相反,我想要的是输入水果名称及其出现次数。即。
{ "_id" : "coconut", "count" : 1 }
{ "_id" : "banana", "count" : 2 }
请您告诉我,如何对这些数组元素进行分组?
答案 0 :(得分:2)
使用以下聚合。您在$match
之后缺少$unwind
阶段。
初始匹配仅过滤文档,其中存在水果数组,其中至少有一个水果来自匹配的输入水果数组。
一旦你$unwind
,它就会解开所有包含其他水果的水果。因此,当您使用第二个匹配时,您过滤水果只包含与输入水果数组匹配的水果。
db.fruits.aggregate([
{"$match":{"state":"Karnataka","fruits":{"$elemMatch":{"$in":["banana","coconut"]}}}},
{"$unwind":"$fruits"},
{"$match":{"fruits":{"$in":["banana","coconut"]}}},
{"$group":{"_id":"$fruits","count":{"$sum":1}}}
])