Get the latest record from mongodb collection

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

    If you are using auto-generated Mongo Object Ids in your document, it contains timestamp in it as first 4 bytes using which latest doc inserted into the collection could be found out. I understand this is an old question, but if someone is still ending up here looking for one more alternative.

    db.collectionName.aggregate(
    [{$group: {_id: null, latestDocId: { $max: "$_id"}}}, {$project: {_id: 0, latestDocId: 1}}])
    

    Above query would give the _id for the latest doc inserted into the collection

提交回复
热议问题