- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
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
Advertisements