MongoDB Indexes Cheatsheet
Quick reference for optimizing MongoDB query performance through effective index creation and management.
MongoDB Index Cheatsheet:
Single-field: db.collection.createIndex({ field: 1 }) • Indexes one field; 1 for ascending, -1 for descending
-- Compound: db.collection.createIndex({ field1: 1, field2: -1 }) • Indexes multiple fields; order matters for sorting
-- Multikey (arrays): db.collection.createIndex({ arrayField: 1 }) • Creates separate index entries for each array element
-- Text: db.collection.createIndex({ textField: "text" }) • Enables full-text search on string content
-- Hashed: db.collection.createIndex({ field: "hashed" }) • Indexes the hash of the field's value; good for sharding
-- Unique: db.collection.createIndex({ field: 1 }, { unique: true }) • Ensures no two documents have the same value for this field
-- Sparse: db.collection.createIndex({ field: 1 }, { sparse: true }) • Only indexes documents where the field exists
-- TTL: db.collection.createIndex({ dateField: 1 }, { expireAfterSeconds: 3600 }) • Automatically removes documents after a specified time
-- Partial: db.collection.createIndex({ field: 1 }, { partialFilterExpression: { condition: true } }) • Only indexes documents meeting specified criteria
-- Wildcard: db.collection.createIndex({ "$**": 1 }) • Indexes all fields in a document, including nested ones
Created on 6/30/2024