Get the latest record from mongodb collection

前端 未结 8 1973
我寻月下人不归
我寻月下人不归 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/

    0 讨论(0)
  • 2020-11-29 18:36

    This is a rehash of the previous answer but it's more likely to work on different mongodb versions.

    db.collection.find().limit(1).sort({$natural:-1})
    
    0 讨论(0)
提交回复
热议问题