Indexes in MongoDB effective execution of query, Otherwise MongoDB must scan all documents inside of the collection to fetch document match the find statement. This scanning process is profoundly inefficient and require the MongoDB to handle a vast volume of information.
Indexes are stores in structured way, that store a little amount of the information set in a simple cross structure. The list stores the estimation of a particular field or set of fields, requested by the estimation of the field as determined in file.
The ensureIndex() Method
In MongoDB the ensureIndex() method is used to create indexes.
db.collectionName.ensureIndex({KEY:1})
ensureIndex will check if the index exists and create it if it doesn't.
Index based on multiple fields is also available in MongoDB. In ensureIndex() method multiple parameters can be passed, to create index based on multiple fields.
db.collectionName.ensureIndex({"title":1,"description":-1})
Background Process:
While creating index for a big collection so make sure to run it on background. Because the indexing process might block other database processes. To run process in background make this option true. The default value of background is false.
db.collectionName.ensureIndex({"title":1,"description":-1}, {background: true})
0 Comment(s)