- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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" } ] }
- Related Articles
- How to index my collection to use a compound multikey index?
- How to improve querying field in MongoDB?
- How to create an index with MongoDB?
- How to remove an array element by its index in MongoDB?
- Insert to specific index for MongoDB array?
- MongoDB query to update array object in index N?
- How to improve the execution time of a query in MongoDB?
- How do I access subdocuments in MongoDB queries?
- Update object at specific Array Index in MongoDB?
- Update array in MongoDB document by variable index?
- How to filter array in subdocument with MongoDB?
- How to count items in array with MongoDB?
- How to index and sort with pagination using custom field in MongoDB?
- How to get the index of an array element in older versions on MongoDB?
- Array index or indexing inner items in MongoDB to fetch values

Advertisements