How to Limit number of documents fetched in MongoDB

You are here : Home / MongoDB Tutorial



Contents of page >

Limit number of documents(record/rows) fetched from collection(table) in MongoDB
Limit method limits number of documents displayed.


First, Let's create new collection and insert document in it >
> db.employee.insert({_id : 1,  firstName:"ankit"})
> db.employee.insert({_id : 2,  firstName:"ankit", salary : 1000 })
> db.employee.insert({_id : 3,  firstName:"sam", salary : 2000 })
> db.employee.insert({_id : 4,  firstName:"neh", salary : 3000 })
First line above will create table (or collection) (if table already exists it will insert documents in it).


1) Display only first 2 documents of collection in MongoDB >
We will use find() and limit() method>
> db.employee.find().limit(2)
Output>
{ "_id" : 1, "firstName" : "ankit" }
{ "_id" : 2, "firstName" : "ankit", "salary" : 1000 }
Display only first 2 documents of collection.


2) Skip first document and display rest of documents of collection in MongoDB >
We will use find() and skip() method >
> db.employee.find().skip(1)
Output>
{ "_id" : 2, "firstName" : "ankit", "salary" : 1000 }
{ "_id" : 3, "firstName" : "sam", "salary" : 2000 }
{ "_id" : 4, "firstName" : "neh", "salary" : 3000 }
Skip 1 document of collection and display rest of documents of collection.


3) FIND Example > Display only 2nd and 3rd document of collection in MongoDB>
We will use find(), limit() and skip() method >
> db.employee.find().skip(1).limit(2)
Output>
{ "_id" : 2, "firstName" : "ankit", "salary" : 1000 }
{ "_id" : 3, "firstName" : "sam", "salary" : 2000 }
Skip 1 document of collection and display 2 documents of collection.


4) FIND Example > Display only 2 documents of collection in MongoDB where salary >= 1000 >
> db.employee.find( { salary : {$gte : 1000} }).limit(2)
Output>
{ "_id" : 2, "firstName" : "ankit", "salary" : 1000 }
{ "_id" : 3, "firstName" : "sam", "salary" : 2000 }




5) SUMMARY>
So in this mongoDB tutorial we learned how to How to Limit number of documents fetched in MongoDB.


1) FIND Example > Display only first 2 documents of collection in MongoDB >
We will use find() and limit() method>
> db.employee.find().limit(2)


2) FIND Example > Skip first document and display rest of documents of collection in MongoDB >
We will use find() and skip() method >
> db.employee.find().skip(1)


3) FIND Example > Display only 2nd and 3rd document of collection in MongoDB>
We will use find(), limit() and skip() method >
> db.employee.find().skip(1).limit(2)


4) FIND Example > Display only 2 documents of collection in MongoDB where salary >= 1000 >
> db.employee.find( { salary : {$gte : 1000} }).limit(2)


Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.


RELATED LINKS>

What is MongoDB - A quick introduction to database


eEdit
Must read for you :