Using findOne in mongodb to get element with max id

后端 未结 5 1809
别那么骄傲
别那么骄傲 2020-12-01 01:18

I am trying to retrieve one element from a mongo collection, the one with the greatest _id field. I know this can be done by querying:

db.collection.find().s         


        
5条回答
  •  情话喂你
    2020-12-01 02:08

    You should use find, like you already are, and not aggregation which will be slower since it needs to scan all the values of _id fields to figure out the max.

    As comments pointed out there is no difference between using find() and findOne() - functionally or elegance-wise. In fact, findOne in the shell (and in the drivers which implement it) is defined in terms of find (with limit -1 and with pretty print in the shell).

    If you really want to do the equivalent of

    db.collection.find().sort({_id:-1}).limit(1).pretty()
    

    as findOne you can do it with this syntax:

    db.collection.findOne({$query:{},$orderby:{_id:-1}})
    

提交回复
热议问题