Facebook Twitter Instagram
    TecAdmin
    • Home
    • Ubuntu 20.04
      • Upgrade Ubuntu
      • Install Java
      • Install Node.js
      • Install Docker
      • Install LAMP Stack
    • Tutorials
      • AWS
      • Shell Scripting
      • Docker
      • Git
      • MongoDB
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    Home»General Articles»Mongodb – Get the last record from collection

    Mongodb – Get the last record from collection

    RahulBy RahulJuly 30, 20221 Min Read

    MongoDB find() method is used to select documents from a specified collection. It also set the cursor position to the selected document.

    The default find() method gets the documents from the start of the collection. In some situations, we need to fetch the last record from a collection. Use the following query to get the last records from a MongoDB collection.

    db.collection.find().limit(1).sort({$natural:-1}) 
    

    The above query provides the single last record only, You can also fetch the multiple records from the end of the MongoDB collection.

    You can set the number of records with limit() method as below:

    db.collection.find().limit(5).sort({$natural:-1}) 
    

    Thanks, Hope this quick how-to tutorial helps you to fulfill your requirements.

    collection find method mongodb query sort
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp
    Previous ArticleRunning a Cron Every 10, 20 or 30 Minutes
    Next Article How to list all collections in MongoDB database

    Related Posts

    How to Import GPG Keys on Ubuntu & Debian (without apt-key)

    2 Mins Read

    Running a Cron job every Sunday (Weekly)

    2 Mins Read

    Scheduling a Python Script with Crontab

    2 Mins Read

    Running cron job every 12 hours (twice a day)

    Updated:August 2, 20221 Min Read

    (Resolved) Key is stored in legacy trusted.gpg Keyring

    Updated:August 9, 20222 Mins Read

    How to list all collections in MongoDB database

    1 Min Read

    Leave A Reply Cancel Reply

    Recent Posts
    • How to Import GPG Keys on Ubuntu & Debian (without apt-key)
    • How To Install Google Chrome On macOS
    • How to Install Minecraft on Ubuntu 22.04 & 20.04
    • Running a Cron job every Sunday (Weekly)
    • Running Multiple Commands At Once in Linux
    Facebook Twitter Instagram Pinterest
    © 2022 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.