w3resource

MongoDB: db.collection.createIndex () method

db.collection.createIndex

The db.collection.createIndex() method is used to builds an index on a collection.

Syntax:

db.collection.createIndex(keys, options)

Parameters:

Name Description Required /
Optional
Type
keys A document that contains the field and value pairs where the field is the index key and the value describes the type of index for that field. For an ascending index on a field, specify a value of 1; for the descending index, specify a value of -1.
MongoDB supports several different index types including text, geospatial, and hashed indexes. See Index Types for more information.
Required document
options A document that contains a set of options that controls the creation of the index. Optional document

Options

The following options are available for all index types unless otherwise specified:

Field Type Description
background boolean Optional. Builds the index in the background so that building an index does not block other database activities. Specify true to build in the background. The default value is false.
unique boolean Optional. Creates a unique index so that the collection will not accept insertion of documents where the index key or keys match an existing value in the index. Specify true to create a unique index. The default value is false.
name string Optional. The name of the index. If unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order.
Whether user specified or MongoDB generated, index names including their full namespace (i.e. database.collection) cannot be longer than the Index Name Limit.
sparse boolean Optional. If true, the index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). The default value is false. See Sparse Indexes for more information.
expireAfterSeconds integer Optional. Specifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection. See Expire Data from Collections by Setting TTL for more information on this functionality. This applies only to TTL indexes.
v index version Optional. The index version number. The default index version depends on the version of mongod running when creating the index. Before version 2.0, this value was 0; versions 2.0 and later use version 1, which provides a smaller and faster index format. Specify a different index version only in unusual situations.
storageEngine document Optional. Allows users to specify the configuration to the storage engine on a per-index basis when creating an index. The value of the storageEngine option should take the following form: { <storage-engine-name>: <options> } Storage engine configuration specified when creating indexes are validated and logged to the oplog during replication to support replica sets with members that use different storage engines.

Sample document in the restaurants collection:


{
  "address": {
     "building": "1007",
     "coord": [ -73.856077, 40.848447 ],
     "street": "Morris Park Ave",
     "zipcode": "10462"
  },
  "borough": "Bronx",
  "cuisine": "Bakery",
  "grades": [
     { "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
     { "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
     { "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
     { "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
     { "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
  ],
  "name": "Morris Park Bake Shop",
  "restaurant_id": "30075445"
}
......

Example: Create an Ascending Index on a Single Field

The following example creates an ascending index on the field cuisine.

> db.restaurants.createIndex( { "cuisine": 1 } );
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1

Example: Create an Index on a Multiple Fields

The following example creates a compound index on the cuisine field (in ascending order) and the zipcode field (in descending order.)

> db.restaurants.createIndex( { "cuisine": 1 , "address.zipcode": -1 } );
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 2,
        "numIndexesAfter" : 3,
        "ok" : 1
}

Retrieve the restaurants data from here

Behavior

The createIndex() method has the behaviors described here.

  • To add or change index options you must drop the index using the dropIndex() method and issue another createIndex() operation with the new options.
    If you create an index with one set of options, and then issue the createIndex() method with the same index fields and different options without first dropping the index, createIndex() will not rebuild the existing index with the new options.
  • If you call multiple createIndex() methods with the same index specification at the same time, only the first operation will succeed, all other operations will have no effect.
  • Non-background indexing operations will block all other operations on a database.
  • MongoDB will not create an index on a collection if the index entry for an existing document exceeds the Maximum Index Key Length.

Previous: db.collection.count() method
Next: db.collection.dataSize() method



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mongodb/shell-methods/collection/db-collection-createIndex.php