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
}
If you want to 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.
Did you find this information useful? If so, consider heading over to my donation page and drop me some support.
Want to ask a question or just chat? Contact me here