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

dak425

Donald Feury

Posted on August 7, 2021

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.

💖 💪 🙅 🚩
dak425
Donald Feury

Posted on August 7, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related