MongoDB

Create an Index in MongoDB

Indexes allow to process and fulfill queries quickly by creating small and efficient representations of the documents in a collection. By default, MongoDB creates an index on the _id field of every collection.

A value of 1 specifies an index that orders items in ascending order and -1 specifies an index that orders items in descending order

 db.users.createIndex( { userid: 1 } ) //Create an Index on a Single Field   

db.users.createIndex( { userid: 1, Email: 1 } ) //Build a Compound Index

db.users.createIndex( { Email: 1 }, { unique: true } ) //Unique Index on a Single Field

db.users.createIndex( { userid: 1, Email: 1 }, { unique: true } ) //Unique Index on a Compund Field

//Hashed indexes compute a hash of the value of a field in a collection and index the hashed value
db.users.createIndex( { _id: "hashed" } ) //Create a Hashed Index

//Background index construction allows read and write operations to continue while building the index.
db.users.createIndex( { Email: 1 }, { background: true } ) //Build Indexes in the Background

//The following operation, creates a sparse index on the users collection that only includes a document in the index if the Email field exists in a document.
//The index excludes all documents that do not include the Email field.
db.users.createIndex( { Email: 1 }, { sparse: true } ) //Create a Sparse Index

Leave a comment