MongoDB – creating and viewing indexes
According to definition from Wikipedia , A database index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional writes and the use of more storage space to maintain the extra copy of data. Indexes are used to quickly locate data without having to search every row in a database table every time a database table is accessed.
Data is stored on disk based storage devices as block of data. These disk block of data are stored much like linked lists. When we perform a linear search on a field that is not sorted then database have to perform N/2
accesses.
While a sorted search based on binary search requires log2 N
disk block accesses. Indexes are a way by which create a data structure that holds field values and a pointer to the corresponding record. Indexes are sorted and allowing Binary Search to be performed on it.
As in relational databases, MongoDB also support indexes for fast retrieval of data. DBMS’s have tables for storing data and we normally add indexes for the columns those are accessed frequently. MongoDB calls tables as Collections and we add indexes on collection columns.
For example we have a collection named students.
db.products.insert( { _id: 1, student_name: "John", email: "john@email.com"} );
Suppose we have 1 million records, we want to search on field student name, Doing a linear search, query will much slower then if we create an index on name field. An index in MongoDB can be created as under:
db.students.ensureIndex({student_name: 1});
This command creates an index on student collection on student_name field. ensureIndex field creates an index only if the same specification index does not already exists.
Indexes can be viewed using following command. It displays list of all indexes in current database.
db.system.indexes.find()
Indexes on a certain collection can be found by this command.
db.collection.getIndexes()
To remove an index, dropIndex() method is used as in the example:
db.accounts.dropIndex({student_name: 1} )
To remove all indexes from a collection we can use following command. (it will remove all indexes except _id indexes)
db.collection.dropIndexes()
To rebuild indexes on a collection we can use the db.collection.reIndex() method to rebuild all indexes on a collection. FFirst this operation drops all indexes, including the _id index, and then rebuilds all
indexes.
db.students.reIndex()