Thursday, February 6, 2014

Sparse Indexes in MongoDB

MongoDB provide flexibility of dynamic fields (columns) for each of the document (row). Unlike in RDBMS or DBMS system where each row has fixed set of columns. In MongoDB each of the documents (row) can have their own set of columns. So it is not mandatory that the two rows will have same columns. This is the beauty of NoSQL database MongoDB.

Sparse Indexes are special kind of indexes which stores references of only those documents (rows) which include the index field. So, if rows do not have the field which is marked in Sparse Index it will not be part of the Index. This saves a lot of disk space.

The syntax to define Sparse Index is following:

db.collection_name.ensureIndex( { Fieldname: 1 or -1 }, { sparse: true /false} )

For example, we have created collection (table) named "Productivity" where documents (rows) have different field. Some documents (rows) do not have Manufacturer field.

Now we will create a Sparse Index on Manufacturer field. We can do this by passing following command.

db.Products.ensureIndex({Manufacturer:1},{sparse:true})



Popular Posts

Blog Archive

Real Time Web Analytics