Stay home. Save Lives
MongoDB Indexes

MongoDB Indexes

MongoDB supoort different types of indexes such as Single Field Indexes, Compound Indexes, Multikey Indexes, Text IndexesWildcard Indexes, 2dsphere Indexes, 2d Indexes, geoHaystack Indexes, Hashed Indexes, and default _id index.

Indexes support the efficient execution of queries in MongoDB queries. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection. Any query if you dont use an index means that full scan occurs on collection. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.

The best approach is that number of calculation must be close to the number of query search. If we use any field on find/sort query, the best use case is to use an index for these fields.F undamentally, indexes in MongoDB are similar to indexes in other database systems. MongoDB defines indexes at the collection level and supports indexes on any field or sub-field of the documents in a MongoDB collection.

db.collection.createIndex( { <name_of_field>: {-1,1} } )

The db.collection.createIndex() method creates an index  with ascending {1} or descending {-1} order.

The db.collection.getIndexes() method gets all indexes from collection.

  • Default _id Index :
    • MongoDB creates a unique index on the _id field during the creation of a collection.
    • The _id index prevents clients from inserting two documents with the same value for the _id field.
    • You cannot drop this index on the _id field.
    • Default _id data type is ObjectId which is auto generated but it can be different data type like String, Long and etc…
    • In sharded clusters, if you do not use the _id field as the shard key, then your application must ensure the uniqueness of the values in the _id field to prevent errors.
  • Single Field Index:
    • MongoDB supports the creation of user-defined ascending/descending indexes on a single field of a document other than _id field.
    • You can also create indexes on embedded document/object as a whole. Not only single field but also embedded document/object
  • Compound Index :
    • MongoDB supports compound indexes which means that more than more fields within s single index
    • A single index structure holds references to multiple fields  within a collection’s documents by using same command with a below like structure
db.collection.createIndex( { <name_1>: {-1,1},  <name_2>: {-1,1}, ..., <name_n>: {-1,1} } )
  • Multikey Index: 
    • MongoDB supports different index types which is working on each element in the array.
    • These multikey indexes support efficient queries against array fields.
    • You cannot create a compound multikey index if more than one to-be-indexed field of a document is an array. For example, consider a collection that contains the following document.
    • Multikey indexes can be constructed over arrays that hold both scalar values [1] (e.g. strings, numbers) and nested documents.
  • Text Index: 
    • MongoDB supports text search queries
    • You can create on string or string array fields.
    • createIndex method is a little different from the single, compound or multikey index usage.
    • You can specify the weights. Please check the $meta usage.
    • You can also use Wildcard Text Indexes
db.reviews.createIndex( { <name>: "text" } )
db.reviews.createIndex( { "$**": "text" } )
  • Wildcard Index: 
    • MongoDB version 4.2 introduces wildcard indexes for supporting queries against unknown or arbitrary fields.
    • MongoDB supports dynamic schemas, applications can query against fields whose names cannot be known in advance or are arbitrary.
    • This means that you can use this index for all different types of fields a nd dynamic schema under this field.
db.reviews.createIndex( { "<name>.$**": {-1,1} } )
  • 2dsphere Index: 
    • MongoDB supports queries that calculate geometries on an earth-like elypric sphere.
    • 2dsphere index supports all MongoDB geospatial queries: queries for inclusion, intersection and proximity
    • You can use sparse property if field is null or an empty array.
    • You can specify a key option to the $geoNear pipeline stage to indicate the indexed field path to use.
    • $near, $nearSphere, $geoWithin, $geoIntersects, $geoNear, $near and lots of query commands can be used for this index.
  • 2d Index: 
    • The 2d index supports calculations on a flat, Euclidean plane.
    • The 2d index also supports distance-only calculations on a sphere (i.e. $nearSphere), but for geometric calculations on a sphere (e.g. $geoWithin), store data as GeoJSON objects and use a 2dsphere index.
    • 2d index can reference two fields. The first must be the location field.
    • 2d compound index constructs queries that select first on the location field, and then filters those results by the additional criteria.
    • A compound 2d index can cover queries.
  • geoHaystack Index:
    • A geoHaystack index is a special index that is optimized to return results over small areas.
    • geoHaystack indexes improve performance on queries that use flat geometry.
    • A 2dsphere index is a better option than a haystack index.
    • 2dsphere indexes allow field reordering; geoHaystack indexes require the first field to be the location field.
  • Hashed Index:
    • Hashed indexes use a hashing function to compute the hash of the value of the index field.
    • MongoDB automatically computes the hashes when resolving queries using hashed indexes. Applications do not need to compute hashes.

 

You may also Like

MongoDB GeoJSON Objects

MongoDB GeoJSON Objects

July 01, 2019

Leave a reply

Your email address will not be published. Required fields are marked *

About Me

I am a dad of two wonderful boys, Utku Efe and Omer Eren, and married with the love of my life, Elif. In addition, I am an academician and AI/ML scientist because I worked more than 15 years in universities, have M.S and Ph.D. thesis and more than 20 scientific papers/presentations and 100 citations. Now people call me as a Principal Developer in my last company :).
I am really hungry on learning new technologies and get more fun while developing new softwares.

Stay Connected

Recent Posts


MongoDB Indexes


What’s Big Query?


Categories

×