简体   繁体   中英

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

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.

We are using MongoDB 3.2, we can't update our systems atm (I wish, but not possible).

You can use $unwind to expand your array, then use $group to sum:

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"}}}
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM