 
  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 does MongoDB index arrays?
MongoDB indexes every value of an array so that you can query for single elements.
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.indexingForArrayElementDemo.insertOne({"StudentFavouriteSubject":["MongoDB","MySQL"]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c8acdca6cea1f28b7aa0816") } Display all documents from a collection with the help of find() method. The query is as follows −
> db.indexingForArrayElementDemo.find().pretty();
The following is the output −
{    "_id" : ObjectId("5c8acdca6cea1f28b7aa0816"),    "StudentFavouriteSubject" : [       "MongoDB",       "MySQL"    ] } Here is the query by which MongoDB index array &minus ;
> db.indexingForArrayElementDemo.ensureIndex({"StudentFavouriteSubject":1}); The following is the output −
{    "createdCollectionAutomatically" : false,    "numIndexesBefore" : 1,    "numIndexesAfter" : 2,    "ok" : 1 } Here is the query for individual array elements −
> db.indexingForArrayElementDemo.find({"StudentFavouriteSubject":"MongoDB"}).pretty(); The following is the output −
{    "_id" : ObjectId("5c8acdca6cea1f28b7aa0816"),    "StudentFavouriteSubject" : [       "MongoDB",       "MySQL"    ] } Let us see another example. The query is as follows −
> db.indexingForArrayElementDemo.find({"StudentFavouriteSubject":"MySQL"}).pretty(); The following is the output −
{    "_id" : ObjectId("5c8acdca6cea1f28b7aa0816"),    "StudentFavouriteSubject" : [       "MongoDB",       "MySQL"    ] }Advertisements
 