How to Apply Indexes in MongoDB
Because MongoDB is a document database, it has indexes that work a little differently. This article explains index concepts that do not exist in relational databases.
MongoDB indexes
In MongoDB, the _id property is basically created automatically as a unique index whenever a document is created. If this is not enough, you can create your own indexes with db.collection.createIndex(). Indexes created with db.collection.createIndex() are B-tree data structure indexes.
MongoDB supports several index types in addition to simple key specifications. The supported index types are as follows.
- Single key
- Compound key
- Multikey
- Geospatial
- Text
- Hashed
“Compound key” and “multikey” have similar names, but they are different. A compound key is a key made from a combination of multiple fields, while a multikey is a key that targets all values included in an array for a field that handles arrays.
Below, we will look at concrete examples of the basic single-field index, compound index, and multikey index.
Basic index creation
You can create an index on a specified collection by running the following command in the mongo shell.
The function is the same in JavaScript code, but JavaScript can specify a callback as the third argument.
Syntax
db.collection.createIndex(keys, options)
Arguments
| Argument | Type | Description |
|---|---|---|
keys |
string/object |
Specifies the field name that has a value. Specify 1 for an ascending key and -1 for a descending key. |
options |
object |
Specifies options for index creation. The available options include unique and collation. There are more options, but remember these for now. |
Examples
Below, we will look at examples of single-field indexes, compound indexes, and multikey indexes.
Creating a single-field index
This section covers three sample codes for creating indexes on a sample document like the following. Because MongoDB is a document database, it can create indexes on embedded fields and embedded documents that do not exist in relational databases.
{
"score": 1034,
"location": { city: "Seoul", county: "Korea Republic of" }
}
Single field
This is the simplest sample code for creating an index on a single field.
> db.collection.createIndex({ score: 1 })
> db.collection.find({ score: 1034 })
> db.collection.find({ score: { $gt: 1000 } })
Embedded field
MongoDB can also specify a document as an attribute value. In this case, fields inside the document, or nested elements, can also be indexed.
> db.collection.createIndex({ "location.city": 1 })
> db.collection.find({ "location.city": "Kyunggi" })
Embedded document
This is similar to an embedded field, but you can also specify the original object. However, note that in this case an exact match is required, including the number and order of attributes.
> db.collection.createIndex({ location: 1 })
> db.collection.find({ city: "Seoul", county: "Korea Republic of" })
Creating a compound-key index
This is a compound-key index, which also exists in relational databases. In MongoDB, it can be created by specifying multiple fields as keys. In a MongoDB compound-key index, the index is effective not only for patterns that match all specified compound keys, but also for patterns that match part of them.
Let’s look at an example of creating a compound-key index for the following sample data.
{
"item": "Apple",
"location": "xxx store",
"stock": 4,
"type": "cases"
}
> db.collection.createIndex({ item: 1, location: 1, stock: 1 })
> db.collection.find({ item: "Apple" })
> db.collection.find({ item: "Apple", location: "xxx store" })
> db.collection.find({ item: "Apple", location: "xxx store", stock: { $gt: 0 } })
In the example above, the index is created as item -> location -> stock, so the leading parts such as item and item -> location can also use the index.
Creating a multikey index
MongoDB also has fields that use arrays as values. Whether an array contains primitive values or objects, a multikey index can be created.
Below, we will look at examples of creating an index on a collection that includes an array field named ratings and searching it.
{ "item": "Apple", ratings: [ 2, 9 ] }
{ "item": "Banana", ratings: [ 4, 3 ] }
An index can be created simply by calling createIndex() for ratings.
> db.collection.createIndex({ ratings: 1 })
Searches on array fields usually use $elemMatch. The following example extracts documents where at least one ratings record is greater than or equal to 3 and less than or equal to 6.
> db.collection.find({ ratings: { $elemMatch: { $gte: 3, $lte: 6 } } })
{ "_id" : ObjectId("5a2d24459c684f917e3ec0c2"), "item" : "XYZ", "ratings" : [ 4, 3 ] }
If you enter the following, it extracts documents where at least one record satisfies greater than or equal to 3 or less than or equal to 6, so all documents are extracted as a result.
> db.collection.find({ ratings: { $gte: 3, $lte: 6 } })
{ "_id" : ObjectId("5a2d24399c684f917e3ec0c1"), "item" : "ABC", "ratings" : [ 2, 9 ] }
{ "_id" : ObjectId("5a2d24459c684f917e3ec0c2"), "item" : "XYZ", "ratings" : [ 4, 3 ] }
References
- MongoDB - db.collection.createIndex()
- MongoDB - Single Field Indexes
- MongoDB - Compound Indexes
- MongoDB - Multikey Indexes