Find a specified amount of records in MongoDB?


To find a specific amount of records, use LIMIT() in MongoDB. The method accepts one number type argument, which is the number of documents that you want to be displayed.

Let us create a collection with documents −

> db.demo549.insertOne({"Name":"Chris"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e32889e5f92834d7f05df")
}
> db.demo549.insertOne({"Name":"David"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e328c9e5f92834d7f05e0")
}
> db.demo549.insertOne({"Name":"Bob"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e328f9e5f92834d7f05e1")
}
> db.demo549.insertOne({"Name":"John"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e32929e5f92834d7f05e2")
}

Display all documents from a collection with the help of find() method −

> db.demo549.find();

This will produce the following output −

{ "_id" : ObjectId("5e8e32889e5f92834d7f05df"), "Name" : "Chris" }
{ "_id" : ObjectId("5e8e328c9e5f92834d7f05e0"), "Name" : "David" }
{ "_id" : ObjectId("5e8e328f9e5f92834d7f05e1"), "Name" : "Bob" }
{ "_id" : ObjectId("5e8e32929e5f92834d7f05e2"), "Name" : "John" }

Following is the query to find a specified amount of records in MongoDB −

> db.demo549.find().limit(2);

This will produce the following output −

{ "_id" : ObjectId("5e8e32889e5f92834d7f05df"), "Name" : "Chris" }
{ "_id" : ObjectId("5e8e328c9e5f92834d7f05e0"), "Name" : "David" }

Updated on: 14-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements