[英]MongoDB Aggregation SUM Array of Arrays by object key
Okay, so I've been searching for a while but couldn't find an answer to this, and I am desperate :P好的,所以我已经搜索了一段时间,但找不到答案,我很绝望:P
I have some documents with this syntax我有一些使用这种语法的文档
{
"period": ISODate("2018-05-29T22:00:00.000+0000"),
"totalHits": 13982
"hits": [
{
// some fields...
users: [
{
// some fields...
userId: 1,
products: [
{ productId: 1, price: 30 },
{ productId: 2, price: 30 },
{ productId: 3, price: 30 },
{ productId: 4, price: 30 },
]
},
]
}
]
}
And I want to retrieve a count of how many products (Independently of which user has them) we have on a period, an example output would be like this:我想检索我们在一段时间内有多少产品(独立于哪个用户拥有它们)的计数,示例输出如下:
[
{
"period": ISODate("2018-05-27T22:00:00.000+0000"),
"count": 432
},
{
"period": ISODate("2018-05-28T22:00:00.000+0000"),
"count": 442
},
{
"period": ISODate("2018-05-29T22:00:00.000+0000"),
"count": 519
}
]
What is driving me crazy is the "object inside an array inside an array" I've done many aggregations but I think they were simpler than this one, so I am a bit lost.让我发疯的是“数组内的数组内的对象”我做了很多聚合,但我认为它们比这个简单,所以我有点迷茫。
I am thinking about changing our document structure to a better one, but we have ~6M documents which we would need to transform to the new one and that's just a mess... but Maybe it's the only solution.我正在考虑将我们的文档结构更改为更好的结构,但是我们有大约 600 万个文档,我们需要将其转换为新的文档,这只是一团糟……但也许这是唯一的解决方案。
We are using MongoDB 3.2, we can't update our systems atm (I wish, but not possible).我们正在使用 MongoDB 3.2,我们无法更新我们的系统 atm(我希望,但不可能)。
You can use $unwind
to expand your array, then use $group
to sum:您可以使用
$unwind
扩展数组,然后使用$group
求和:
db.test.aggregate([
{$match: {}},
{$unwind: "$hits"},
{$project: {_id: "$_id", period: "$period", users: "$hits.users"}},
{$unwind: "$users"},
{$project: {_id: "$_id", period: "$period", subCout: {$size: "$users.products"}}},
{$group: {"_id": "$period", "count": {$sum: "$count"}}}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.