How to query MongoDB with a LIMIT?


To query MongoDB with limit, use LIMIT() method. Let us create a collection with documents −

> db.demo58.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e285f8fcfb11e5c34d8991f")
}
> db.demo58.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e285f93cfb11e5c34d89920")
}
> db.demo58.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e285f94cfb11e5c34d89921")
}
> db.demo58.insertOne({"Name":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e285f99cfb11e5c34d89922")
}

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

> db.demo58.find();

This will produce the following output −

{ "_id" : ObjectId("5e285f8fcfb11e5c34d8991f"), "Name" : "David" }
{ "_id" : ObjectId("5e285f93cfb11e5c34d89920"), "Name" : "David" }
{ "_id" : ObjectId("5e285f94cfb11e5c34d89921"), "Name" : "David" }
{ "_id" : ObjectId("5e285f99cfb11e5c34d89922"), "Name" : "Mike" }

Following is the query with LIMIT in MongoDB −

> v=2;
2
> d=db.demo58.find({"Name":"David"}).limit(v+1);
{ "_id" : ObjectId("5e285f8fcfb11e5c34d8991f"), "Name" : "David" }
{ "_id" : ObjectId("5e285f93cfb11e5c34d89920"), "Name" : "David" }
{ "_id" : ObjectId("5e285f94cfb11e5c34d89921"), "Name" : "David" }
> m=d.size() > v;

This will produce the following output −

True

Updated on: 03-Apr-2020

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements