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"
   ]
}

Updated on: 30-Jul-2019

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements