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