Use the limit method to retrieve a specific number of documents from MongoDB
Donald Feury
Posted on August 7, 2021
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
}
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)
Will return the following:
{
"name": "John Doe",
"email": "test@test.com",
"admin": false
},
{
"name": "Jane Doe",
"email": "test2@test2.com",
"admin": false
}
The argument passed into limit
determines the maximum number of documents the cursor from find
will return.
💖 💪 🙅 🚩
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.