Wednesday, February 5, 2014

Compound Index in MongoDB

Compound Indexes are created on two or more columns. MongoDB allows up to 31 fields which can be included in the compound index. Technically with Compound Index one single index store reference of multiple fields. To create Compound Index the syntax is following:

db.collection_name.ensureIndex({field_name1:Sorting_order, field_name2: 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.

For example:

To create Compund Index for employeeList collection (table) we can issue following command:

db.employeeList.ensureIndex({"EmpName":1,"Salary":-1})

Here we are creating compound Index on two fields – EmpName and Salary.



Popular Posts

Blog Archive

Real Time Web Analytics