Showing posts with label Compound Index. Show all posts
Showing posts with label Compound Index. Show all posts

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.



Indexes in MongoDB

Like other RDBMS system such as Oracle, SQL Server, DB2 etc. MongoDB provide support for Indexes. Indexes are mainly use for faster performance of read operations. As you now Collection (table) holds the data in MongoDB. Every time we wish to query the data in collection we ask MongoDB to scan all the data and return it to us. Scanning all the data is time consuming process. The more data the collection (table) holds, the more time it takes to read the data.

Indexes come to help here. Indexes stores small part of large data set stored in collection (table) in an order list.

In MongoDB there are two type of Index

1.     System Defined Index
2.     User Defined Index

System Defined Index

MongoDB by default add _Id() index in all the collection (table). The _Id() field is a unique index. A unique index does not allow duplicate value in the field. The _Id() field is stored with each of the document (row) in a Collection (table). A user cannot drop or delete the _Id() index. The default value in this field is an ObjectID. It is a by default added Primary key by MongoDB in every Collection.

So, every time we issue an Insert() method to add document into collection, MongoDB ensue that document is stored with a _Id() field.

User Defined Indexes

MongoDB has provided 6 user defined indexes which can be created by the users as per their requirement.

1.    Unique Index
2.    Compound Index
3.    Array Index
4.    Time to Live (TTL) Index
5.    Text Index
6.    Geospatial Index



Popular Posts

Real Time Web Analytics