Get the latest record from mongodb collection

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

    Yet another way of getting the last item from a MongoDB Collection (don't mind about the examples):

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

    Normal Projection

    > db.Sports.find()
    { "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2017", "Body" : "Again, the Pats won the Super Bowl." }
    { "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
    { "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
    

    Sorted Projection ( _id: reverse order )

    > db.Sports.find().sort({'_id':-1})
    { "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
    { "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
    { "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2018", "Body" : "Again, the Pats won the Super Bowl" }
    

    sort({'_id':-1}), defines a projection in descending order of all documents, based on their _ids.

    Sorted Projection ( _id: reverse order ): getting the latest (last) document from a collection.

    > db.Sports.find().sort({'_id':-1}).limit(1)
    { "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
    

提交回复
热议问题