Get the latest record from mongodb collection

前端 未结 8 2103
我寻月下人不归
我寻月下人不归 2020-11-29 17:40

I want to know the most recent record in a collection. How to do that?

Note: I know the following command line queries works:

1. db.test.find().sort(         


        
8条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 18:33

    This is how to get the last record from all MongoDB documents from the "foo" collection.(change foo,x,y.. etc.)

    db.foo.aggregate([{$sort:{ x : 1, date : 1 } },{$group: { _id: "$x" ,y: {$last:"$y"},yz: {$last:"$yz"},date: { $last : "$date" }}} ],{   allowDiskUse:true  })
    

    you can add or remove from the group

    help articles: https://docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group

    https://docs.mongodb.com/manual/reference/operator/aggregation/last/

提交回复
热议问题