gpt4 book ai didi

MongoDB - 具有嵌套字段的组复合键

转载 作者:行者123 更新时间:2023-12-02 00:32:21 25 4
gpt4 key购买 nike

我在 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
}
]
}
]
}
]
}
]
}

我在寻找什么

我希望对“值”字段求和并按这些字段进行分组:

  1. 类型
  2. 事件名称
  3. 站点名称

因此,对于我拥有的文档,我希望得到:

  1. 对于 {"Party","After Party","club8"} 组合,总金额为 40
  2. 对于组合 {"Party","After Party","PostParty"} 总和为 90

我尝试过的

我尝试将聚合运算符与 _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' }
}
});

结果

一个文档,包含 3 个数组 - 一个数组对应我希望分组的每个值。 “siteName”数组包含“siteName”可用的 2 个值。 “总计”似乎没有总结任何内容,并且只出现一次 - 我希望在文档中的每个“SiteName”值旁边看到它。

 {
"_id":{
"type":[
"Party"
],
"name":[
[
"After Party"
]
],
"siteName":[
[
[
"club8",
"PostParty"
]
]
]
},
"total":0
}

我使用“聚合”的方式是否错误,或者我使用的模式不适合我的目标?谢谢。

最佳答案

您需要先申请$unwind所有数组上的运算符,以便您可以使用 $group 进行聚合计算运算符(operator)稍后在管道阶段。最后,您将得到这样的聚合管道:

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
}

关于MongoDB - 具有嵌套字段的组复合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29879825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com