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" }

Updated on: 30-Mar-2020

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements