Saturday 21 February 2015

mongoDB : Indexing documents


“ensureIndex” method is used to creates an index on the specified field if the index does not already exist.

Syntax
db.collection_name.ensureIndex(keys, options)

Parameter
Type
Description
keys
document
Document contains key-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 descending index, specify a value of -1.
options
document
Optional. A document that contains a set of options that controls the creation of the index.

options
There are set of options available to control the creation of index.

Parameter
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.
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.
expireAfterSeconds
integer
Optional. Specifies a value, in seconds, as a TTL(Time to live) to control how long MongoDB retains documents in this collection.
v
index version
Optional. The index version number. The default index version depends on the version of mongod running when creating the index.


For more information about options, refer following link.

db.employee.ensureIndex({"firstName":1,"lastName":-1})
Above statement creates index on fields “firstName”, “lastName”. “firstName” in Ascending order, “lastName” in descending order.

> db.employee.ensureIndex({"firstName":1,"lastName":-1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
>


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment