Raj Nandan Sharma
Raj Nandan Sharma

Reputation: 3862

mongo aggregate query (multiple group by)

I have a data like this

[
    {
        slave_id:1,
        data:{
            a:1
        },
        ts:2018-01-19T06:39:20.000Z
    },
    {
        slave_id:1,
        data:{
            a:2
        },
        ts:2018-01-19T06:39:21.000Z
    },
    {
        slave_id:2,
        data:{
            a:3
        },
        ts:2018-01-19T06:39:22.000Z
    },
    {
        slave_id:2,
        data:{
            a:4
        },
        ts:2018-01-19T06:39:23.000Z
    }
]

I want an aggregate query that gives me the sum of "a" for the last record of each "slave_id"

That is the result should be

2(last value form slave_id=1)+4(last value form slave_id=2) =6

Upvotes: 0

Views: 40

Answers (1)

s7vr
s7vr

Reputation: 75924

You can use below query.

db.collection.aggregate([
    {$unwind:"$slaves"},
    {$sort:{"ts": 1}},
    {$group:{_id:"$slave_id", lastele:{$last:"$data.a"}}},
    {$group:{_id:null, sum:{$sum:"$lastele"}}},
])

Upvotes: 1

Related Questions