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       }    ] }
Updated on: 2019-07-30T22:30:25+05:30

146 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements