- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB Aggregate to limit the number of records
To limit the number of records, use $limit in MongoDB. Let us create a collection with documents −
> db.demo240.insertOne({"StudentName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e441d969af932883c61ea3c") } > db.demo240.insertOne({"StudentName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e441d9a9af932883c61ea3d") } > db.demo240.insertOne({"StudentName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e441d9d9af932883c61ea3e") } > db.demo240.insertOne({"StudentName":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5e441da19af932883c61ea3f") }
Display all documents from a collection with the help of find() method −
> db.demo240.find();
This will produce the following output −
{ "_id" : ObjectId("5e441d969af932883c61ea3c"), "StudentName" : "Chris" } { "_id" : ObjectId("5e441d9a9af932883c61ea3d"), "StudentName" : "Bob" } { "_id" : ObjectId("5e441d9d9af932883c61ea3e"), "StudentName" : "David" } { "_id" : ObjectId("5e441da19af932883c61ea3f"), "StudentName" : "Mike" }
Following is the query to limit the number of records in MongoDB −
> db.demo240.aggregate( { $limit : 3 });
This will produce the following output −
{ "_id" : ObjectId("5e441d969af932883c61ea3c"), "StudentName" : "Chris" } { "_id" : ObjectId("5e441d9a9af932883c61ea3d"), "StudentName" : "Bob" } { "_id" : ObjectId("5e441d9d9af932883c61ea3e"), "StudentName" : "David" }
- Related Articles
- Is there a way to limit the number of records in a certain MongoDB collection?
- MongoDB query to insert but limit the total records
- How to limit the number of records, while retrieving data from a MongoDB collection using Java?
- Get number of records in MongoDB?
- Limit the number of documents in a collection in MongoDB?
- Aggregate records in JavaScript
- Limit number of values in a field using MongoDB?
- Limit number of values in a field with MongoDB?
- MongoDB aggregate query to sort
- MongoDB aggregate $slice to get the length of the array
- MongoDB query to implement aggregate function
- MongoDB query to aggregate nested array
- How to use MongoDB Aggregate to sort?
- MongoDB query to limit the returning values of a field?
- How to aggregate array documents in MongoDB?

Advertisements