MongoDB-具有嵌套字段的组复合键
我在mongodb中有此文档:MongoDB-具有嵌套字段的组复合键,mongodb,Mongodb,我在mongodb中有此文档: { "_id":"26/04/2015 09:50", "reservations":130, "Event_types":[ { "type":"Party", "events":[ { "eventName":"After Party", "total_count":130, "by":[ {
{
"_id":"26/04/2015 09:50",
"reservations":130,
"Event_types":[
{
"type":"Party",
"events":[
{
"eventName":"After Party",
"total_count":130,
"by":[
{
"siteName":"club8",
"countArray":[
{
"bucket":"default",
"value":40
}
]
},
{
"siteName":"PostParty",
"countArray":[
{
"bucket":"1",
"value":70
},
{
"bucket":"2",
"value":20
}
]
}
]
}
]
}
]
}
我在找什么
我希望对“值”字段求和,并按以下字段分组:
db.testing.aggregate(
{
$group : {
_id :
{
type:'$Event_types.type',
name: '$Event_types.events.eventName',
siteName: '$Event_types.events.by.siteName'
}
, total : { $sum : '$Event_types.events.by.countArray.value' }
}
});
结果
一个文档,有3个数组-我希望按每个值分组一个。“siteName”数组包含可用于“siteName”的2个值。“total”似乎并没有总结任何东西,它只出现了一次——我希望它出现在文档中每个“SiteName”值的旁边
{
"_id":{
"type":[
"Party"
],
"name":[
[
"After Party"
]
],
"siteName":[
[
[
"club8",
"PostParty"
]
]
]
},
"total":0
}
我使用“聚合”的方式是否错误,或者我使用的模式是否不适合我的目标?
谢谢。您需要首先在所有数组上应用运算符,以便稍后在管道阶段使用运算符进行聚合计算。最终,您将得到如下聚合管道:
db.testing.aggregate([
{ "$unwind": "$Event_types" },
{ "$unwind": "$Event_types.events" },
{ "$unwind": "$Event_types.events.by" },
{ "$unwind": "$Event_types.events.by.countArray" },
{
"$group": {
"_id": {
"type": "$Event_types.type",
"name": "$Event_types.events.eventName",
"siteName": "$Event_types.events.by.siteName"
},
"total": {
"$sum": "$Event_types.events.by.countArray.value"
}
}
},
{
"$project": {
"_id": 0,
"type": "$_id.type",
"name": "$_id.name",
"siteName": "$_id.siteName",
"total": 1
}
}
]);
输出
/* 1 */
{
"result" : [
{
"total" : 90,
"type" : "Party",
"name" : "After Party",
"siteName" : "PostParty"
},
{
"total" : 40,
"type" : "Party",
"name" : "After Party",
"siteName" : "club8"
}
],
"ok" : 1
}