DEV Community

Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

1 1

Use the limit method to retrieve a specific number of documents from MongoDB

For a full overview of MongoDB and all my posts on it, check out my overview.

While you can use the find method to read data back out of MongoDB and the findOne method is a MongoDB query to pull specifically one result, you can use the limit method after using find to retrieve a specific number of documents.

Given this dataset in a collection called users:

{
    "name": "John Doe",
    "email": "test@test.com",
    "admin": false
},
{
    "name": "Jane Doe",
    "email": "test2@test2.com",
    "admin": false
},
{
    "name": "Bob Doe",
    "email": "bob@bob.com",
    "admin": true
},
{
    "name": "Your Mom",
    "email": "koolkid@someplace.com",
    "admin": false
}

Enter fullscreen mode Exit fullscreen mode

If you want to get only the first two documents from the users collection, you can chain the limit method after using find like so:

db.users.find().limit(2)

Enter fullscreen mode Exit fullscreen mode

Will return the following:

{
    "name": "John Doe",
    "email": "test@test.com",
    "admin": false
},
{
    "name": "Jane Doe",
    "email": "test2@test2.com",
    "admin": false
}

Enter fullscreen mode Exit fullscreen mode

The argument passed into limit determines the maximum number of documents the cursor from find will return.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay