Wednesday, February 5, 2014

Unique or Single field Index in MongoDB

Unique or Single field indexes are created on one field (column) of Collection (table). To create a Unique or Single field index the syntax is following:

db.collection_name.ensureIndex({field_name:Sorting_order }, {parameters})

Sorting_order could be Ascending (1) or Descending (-1). By putting the sorting_order you are telling MongoDB to create a unique index on the field and store the value in a specific order. Unique Index does not allow duplicate entries in the field (columns).

For example:

To create Unique Index for deptdetails collection (table) we can issue following command:

db.deptdetails.ensureIndex({"DeptName":1})

Popular Posts

Blog Archive

Real Time Web Analytics