Mongodb Query: Latest record by date for each item

前端 未结 2 717
天涯浪人
天涯浪人 2021-01-12 06:22

There are six devices in a collection, each has many records, some have records of new dates and some have week or/and month older. I need a query which returns latest last

相关标签:
2条回答
  • 2021-01-12 06:28

    Try with following snippet

    db.collection.aggregate([
                {$group: {
                        "_id": "$device_id",
                        "gateway_id": {"$last":"$gateway_id"},
                         data: {$last: '$data'},
                         date: {$last: '$date_time'},
                    }},
                {$project: {
                         "device_id": "$_id",
                          "gateway_id": "$gateway_id",
                          "data": "$data",
                          "date_time": "$date"
                      }},
                {$sort: {
                        'date': -1
                    }}
            ])
    

    In above query group by device id and date, data, and gateway_id will be latest in each row.

    Output is-

    {
        "result" : [ 
            {
                "_id" : 29,
                "gateway_id" : 1,
                "data" : [ 
                    {
                        "r" : 203,
                        "v" : 3002
                    }, 
                    {
                        "r" : 221,
                        "v" : 3006
                    }
                ],
                "device_id" : 29,
                "date_time" : "a"
            }, 
            {
                "_id" : 28,
                "gateway_id" : 1,
                "data" : [ 
                    {
                        "r" : 203,
                        "v" : 3002
                    }, 
                    {
                        "r" : 221,
                        "v" : 3006
                    }
                ],
                "device_id" : 28,
                "date_time" : "b"
            }, 
            {
                "_id" : 27,
                "gateway_id" : 1,
                "data" : [ 
                    {
                        "r" : 203,
                        "v" : 3642
                    }, 
                    {
                        "r" : 221,
                        "v" : 3666
                    }
                ],
                "device_id" : 27,
                "date_time" : "a"
            }
        ],
        "ok" : 1
    }
    

    Thanks

    0 讨论(0)
  • 2021-01-12 06:42

    use findOne instead of find Query db.collection.findOne({})

    0 讨论(0)
提交回复
热议问题