Get the latest record from mongodb collection

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

    I need a query with constant time response

    By default, the indexes in MongoDB are B-Trees. Searching a B-Tree is a O(logN) operation, so even find({_id:...}) will not provide constant time, O(1) responses.

    That stated, you can also sort by the _id if you are using ObjectId for you IDs. See here for details. Of course, even that is only good to the last second.

    You may to resort to "writing twice". Write once to the main collection and write again to a "last updated" collection. Without transactions this will not be perfect, but with only one item in the "last updated" collection it will always be fast.

提交回复
热议问题