[英]MongoDB - group composite key with nested fields
I have this document in mongodb: 我在mongodb中有这个文件:
{
"_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
}
]
}
]
}
]
}
]
}
What I'm looking for 我正在寻找什么
I wish to sum the "value" field and group by these fields: 我希望通过以下字段对“值”字段和组进行求和:
So for the document I have I would expect to get: 所以对于我希望得到的文件:
What I've tried 我试过的
I've tried using the aggregate operator with a composite key for the _id: 我已经尝试使用聚合运算符和_id的复合键:
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' }
}
});
The results 结果
one document, with 3 arrays - one for every value I wish to group by. 一个文档,有3个数组 - 每个我希望分组的值。 The "siteName" array contains the 2 values available for "siteName". “siteName”数组包含“siteName”可用的2个值。 The "total" doesn't seem to sum up anything, and it appears only once - I expected to see it next to each "SiteName" value in the document. “总数”似乎没有总结任何东西,它只出现一次 - 我希望在文档中的每个“SiteName”值旁边看到它。
{
"_id":{
"type":[
"Party"
],
"name":[
[
"After Party"
]
],
"siteName":[
[
[
"club8",
"PostParty"
]
]
]
},
"total":0
}
Am I using "aggregate" the wrong way or is the schema I'm using not fit for my goal? 我是以错误的方式使用“聚合”还是我使用的架构不适合我的目标? Thank you. 谢谢。
You need to first apply the $unwind
operator on all the arrays so that you can do the aggregation calculations with the $group
operator later in the pipeline stages. 您需要首先在所有数组上应用$unwind
运算符,以便稍后在管道阶段使用$group
运算符进行聚合计算。 In the end you will end up with an aggregation pipeline like this: 最后,您将得到一个像这样的聚合管道:
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
}
}
]);
Output 产量
/* 1 */
{
"result" : [
{
"total" : 90,
"type" : "Party",
"name" : "After Party",
"siteName" : "PostParty"
},
{
"total" : 40,
"type" : "Party",
"name" : "After Party",
"siteName" : "club8"
}
],
"ok" : 1
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.