 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- 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 querying field in MongoDB?
To improve querying field in MongoDB, you need to use index. Let us create a collection with documents
> db.improveQueryDemo.insertOne( ... { ...    "PlayerDetails":[ ...       {"PlayerName": "John", "PlayerGameScore": 5690}, ...       {"PlayerName": "Carol", "PlayerGameScore": 2690}, ...    ] ... } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5c9dbaf875e2eeda1d5c3670") } Following is the query to display all documents from a collection with the help of find() method
> db.improveQueryDemo.find().pretty();
This will produce the following output
{    "_id" : ObjectId("5c9dbaf875e2eeda1d5c3670"),    "PlayerDetails" : [       {          "PlayerName" : "John",          "PlayerGameScore" : 5690       },       {          "PlayerName" : "Carol",          "PlayerGameScore" : 2690       }    ] } Now you need to create an index on the field to improve querying. Following is the query
> db.improveQueryDemo.ensureIndex({"PlayerDetails.PlayerName":1}); This will produce the following output
{    "createdCollectionAutomatically" : false,    "numIndexesBefore" : 1,    "numIndexesAfter" : 2,    "ok" : 1 } Now you can search by the exact match. Following is the query
> db.improveQueryDemo.find({"PlayerDetails.PlayerName":"Carol"}).pretty(); This will produce the following output
{    "_id" : ObjectId("5c9dbaf875e2eeda1d5c3670"),    "PlayerDetails" : [       {          "PlayerName" : "John",          "PlayerGameScore" : 5690       },       {          "PlayerName" : "Carol",          "PlayerGameScore" : 2690       }    ] }Advertisements
 