gpt4 book ai didi

MongoDB:在对象数组内部的数组中聚合分组对象

转载 作者:可可西里 更新时间:2023-11-01 09:54:01 24 4
gpt4 key购买 nike

我需要在 mongodb 聚合管道内按 mallId 对选票内的对象进行分组。多年来一直在寻找答案,但我对 mongodb 不太熟悉,所以我有点迷茫。谁能帮帮我?

     [
{
"_id": "Specialty Retailer",
"votes": [
{
"mallId": "59ddea3718a03a4e81f289f5",
"count": 13
},
{
"mallId": "59ddea3718a03a4e81f289f5",
"count": 270
},
{
"mallId": "59ddea3718a03a4e81f289f5",
"count": 13
},
{
"mallId": "59ddea3718a03a4e81f289f5",
"count": 2
},
{
"mallId": "59ddea3718a03a4e81f289f5",
"count": 15
},
{
"mallId": "59ddea3718a03a4e81f289f5",
"count": 2
}
]
}
]

最佳答案

给定以下文档结构

{
"_id" : ObjectId("5a020ea06216d24dd6050a07"),
"arr" : [
{
"_id" : "Specialty Retailer",
"votes" : [
{
"mallId" : "59ddea3718a03a4e81f289f5",
"count" : 13
},
{
"mallId" : "59ddea3718a03a4e81f289f5",
"count" : 270
}
]
}
]
}

这个查询应该让你继续:

db.collection.aggregate({
$unwind: "$arr"
}, {
$unwind: "$arr.votes"
}, {
$group: {
"_id": {
"_id": "$_id",
"arrId": "$arr._id",
"mallId": "$arr.votes.mallId"
},
"totalCount": {
$sum: "$arr.votes.count"
}
}
})

关于MongoDB:在对象数组内部的数组中聚合分组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47162709/

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