Mongo $ group数组元素基于输入数组

问题描述 投票:-1回答:1

我的收藏品有以下格式 -

{
 "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 }

你能告诉我,如何对这些数组元素进行分组?

mongodb aggregation-framework
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.