- 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
Why is MongoDB taking too much time to find the record?
In this case, use the concept of index on a particular field. Let us first create a collection with documents. Here, we have created index as well using createIndex() −
> db.decreasetimeusingindex.createIndex({"StudentName":1}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.decreasetimeusingindex.insertOne({"StudentName":"John Smith","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5e03960af5e889d7a51994ff") } > db.decreasetimeusingindex.insertOne({"StudentName":"John Doe","StudentAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5e039611f5e889d7a5199500") } > db.decreasetimeusingindex.insertOne({"StudentName":"Adam Smith","StudentAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5e03961df5e889d7a5199501") }
Following is the query to display all documents from a collection with the help of find() method −
> db.decreasetimeusingindex.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e03960af5e889d7a51994ff"), "StudentName" : "John Smith", "StudentAge" : 21 } { "_id" : ObjectId("5e039611f5e889d7a5199500"), "StudentName" : "John Doe", "StudentAge" : 24 } { "_id" : ObjectId("5e03961df5e889d7a5199501"), "StudentName" : "Adam Smith", "StudentAge" : 22 }
Following is the query to find a specific record −
> db.decreasetimeusingindex.find({"StudentName":"Adam Smith"});
This will produce the following output −
{ "_id" : ObjectId("5e03961df5e889d7a5199501"), "StudentName" : "Adam Smith", "StudentAge" : 22 }
Advertisements