Compound or multiple fields index in MongoDB

Compound indexes in MongoDB

A compound index in MongoDB is an index that are contained from multiple fields where a single index structure holds references to multiple fields within a collection’s documents.

Create a Compound Index

To create a compound index use an operation that resembles the following prototype:

db.collection.createIndex( {
	<field1>: <type>, <field2>: <type2>, ... 
} )

The value of the field in the index specification describes the kind of index for that field. For example, a value of 1 specifies an index that orders items in ascending order. A value of -1 specifies an index that orders items in descending order.

The order of the fields listed in a compound index is important. The index will contain references to documents sorted first by the values of the field1 and, within each value of the field1, sorted by values of the field2. here is some examples:

  • When looking only for field1 MongoDB can use this index to speed up your query because it's sorted in the coumpound index.
  • When looking for field2 or sorted field2 that a specific field1 has.

Create a compound indexes in MongoDB example

Inserting Data

Consider a collection named articles that holds documents that resemble the following document:

{ "_id" : ObjectId("5e35a076890d645061ea7db8"), author: "yamicode", "name" : "article 1", category: "sports", views: 10 }
{ "_id" : ObjectId("5e35a076890d645061ea7db9"), author: "yamicode", "name" : "article 2", category: "finance", views: 20 }
{ "_id" : ObjectId("5e35a076890d645061ea7dba"), author: "john", "name" : "article 3", category: "sports", views: 5}
{ "_id" : ObjectId("5e35a076890d645061ea7dbb"), author: "john", "name" : "article 4", category: "web", views: 30 }

Example of equality

Index creation
db.articles.createIndex({"author": 1, "category": 1})
Explaining the result

We will use the explain method to see if mongodb will use our index or not.

db.articles.explain().find({"author": "yamicode", "category": "sports"})
Result
{
	...
	"stage" : "IXSCAN",
	"indexName" : "author_1_category_1",
	...
}

Example of sort

Index creation
db.articles.createIndex({"author": 1, "views": 1})
Explaining the result

We will use the explain method to see if mongodb will use our index or not.

db.articles.explain().find({"author": "yamicode"}).sort({"views": 1})
Result
{
	...
	"stage" : "IXSCAN",
	"indexName" : "author_1_views_1",
	...
}