Thursday, 12 November 2015

mongodb $last doesn't work


I used to have a mongodb search:

db['xxxx'].aggregate(
    [
        {$match:{ type:"App", deviceId:"xxxxx"}},
        {
            $group: {
                _id: {deviceId: '$deviceId'},
                latestDate: { $last: "$date"}
            }
        }
    ]
 )

It always gives me wrong result (not the latest data).

Solution:

I finally found that I used $last wrongly.   $last must be used with $sort.

https://docs.mongodb.org/v3.0/reference/operator/aggregation/sort/

the right search is:

db['xxxx'].aggregate(
    [
        {$match:{ type:"App", deviceId:"xxxxx"}},
        { $sort: { deviceId: 1, type:1, date: 1 } },
        {
            $group: {
                _id: {deviceId: '$deviceId'},
                latestDate: { $last: "$date"}
            }
        }
    ]
 )

No comments:

Post a comment