我有以下数据。我想按数组中的字段进行分组。
{
"_id" : ObjectId("54e73137758646882f445383"),
"items" : [
{
"name" : "one",
"quality" : "high"
},
{
"name" : "one",
"quality" : "low"
},
{
"name" : "two",
"quality" : "high"
}
]
}
/* 1 */
{
"_id" : ObjectId("54e73166758646882f445384"),
"items" : [
{
"name" : "two",
"quality" : "high"
},
{
"name" : "three",
"quality" : "low"
},
{
"name" : "four",
"quality" : "medium"
}
]
}
我想按名称和质量进行分组,我想得到点数。
这就是我试过的
db.testColl.aggregate( {$group : {
_id : {itemsName : "$items.name" ,itemsQuality : "$items.quality" },
count : {$sum : 1}
}})
我得到了结果
{
"result" : [
{
"_id" : {
"itemsName" : [
"two",
"three",
"four"
],
"itemsQuality" : [
"high",
"low",
"medium"
]
},
"count" : 1
},
{
"_id" : {
"itemsName" : [
"one",
"one",
"two"
],
"itemsQuality" : [
"high",
"low",
"medium"
]
},
"count" : 1
}
],
"ok" : 1
}
预期结果:
{
"result" : [
{
"_id" : {
"itemsName" : one,
"itemsQuality" : high
},
"count" : 1
},
{
"_id" : {
"itemsName" : one,
"itemsQuality" : low
},
"count" : 1
},
{
"_id" : {
"itemsName" : two,
"itemsQuality" : high
},
"count" : 2
},
....
],
"ok" : 1
}
有可能吗?如果是这样帮助我这样做? 如果不可能,请更正我的结构以达到结果。
答案 0 :(得分:2)
尝试这样可以解决您的问题
db.collectionName.aggregate({
"$unwind": "$items"
}, {
"$group": {
"_id": {
"itemsName": "$items.name",
"itemsQuality": "$items.quality"
},
"count": {
"$sum": 1
}
}
})