Dino Geek, try to help you

How to retrieve the last record in MongoDB?


You can retrieve the last record in MongoDB by sorting your collection in descending order and then limiting the result to 1.

Here is an example in MongoDB shell:

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

In this example, ‘collection’ is the name of the collection where the data is stored.

This works because MongoDB assigns unique ObjectIds to each document which are generated considering the timestamp, this way the latest document would have the highest \_id.

Sorting in descending order (`-1`) returns documents in the reverse order they were inserted, i.e., the latest document first. And `limit(1)` returns only one document, which would be the latest one.

Just make sure you have an index on the field being sorted on (`db.collection.createIndex({_id: -1})`), otherwise sorting could be slow on large collections.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use