- 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 improve the execution time of a query in MongoDB?
To improve the execution time of a query, use index along with unique:true. Let us create a collection with documents −
> db.demo193.createIndex({"LastName":1},{unique:true}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo193.insertOne({"FirstName":"John","LastName":"Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3ade1803d395bdc21346d1") } > db.demo193.insertOne({"FirstName":"John","LastName":"Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3ade1f03d395bdc21346d2") } > db.demo193.insertOne({"FirstName":"David","LastName":"Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3ade2803d395bdc21346d3") }
Display all documents from a collection with the help of find() method −
> db.demo193.find();
This will produce the following output −
{ "_id" : ObjectId("5e3ade1803d395bdc21346d1"), "FirstName" : "John", "LastName" : "Doe" } { "_id" : ObjectId("5e3ade1f03d395bdc21346d2"), "FirstName" : "John", "LastName" : "Smith" } { "_id" : ObjectId("5e3ade2803d395bdc21346d3"), "FirstName" : "David", "LastName" : "Miller" }
Following is the query to find a value with quicker execution time −
> db.demo193.find({"LastName":"Smith"});
This will produce the following output −
{ "_id" : ObjectId("5e3ade1f03d395bdc21346d2"), "FirstName" : "John", "LastName" : "Smith" }
Advertisements