How to improve MongoDB queries with multikey index in array?


For this, use $elemMatch, which is used to query nested objects. Let us create a collection with documents −

> db.demo444.insertOne(
...    {
...       "Information": [{
...          id:1,
...          Name:"Chris"
...       }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e78ea87bbc41e36cc3caebf")
}
> db.demo444.insertOne(
...    {
...       "Information": [{
...          id:2,
...          Name:"David"
...       }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e78ea87bbc41e36cc3caec0")
}
> db.demo444.insertOne(
...    {
...       "Information": [{
...          id:3,
...          Name:"Bob"
...       }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e78ea88bbc41e36cc3caec1")
}

Display all documents from a collection with the help of find() method −

> db.demo444.find();

This will produce the following output −

{ "_id" : ObjectId("5e78ea87bbc41e36cc3caebf"), "Information" : [ { "id" : 1, "Name" : "Chris" } ] }
{ "_id" : ObjectId("5e78ea87bbc41e36cc3caec0"), "Information" : [ { "id" : 2, "Name" : "David" } ] }
{ "_id" : ObjectId("5e78ea88bbc41e36cc3caec1"), "Information" : [ { "id" : 3, "Name" : "Bob" } ] }

Following is the query to improve queries with multikey index in array −

> db.demo444.find({
...    "Information":{
...       $elemMatch:{
...          id:2,
...          Name:"David"
...       }
...    }
... })

This will produce the following output −

{ "_id" : ObjectId("5e78ea87bbc41e36cc3caec0"), "Information" : [ { "id" : 2, "Name" : "David" } ] }

Updated on: 06-Apr-2020

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements