Index types
Besides ordinary indexes MongoDB offers multikey, text, geospatial, hashed, TTL, partial and wildcard indexes.
In this page:
Syntax
db.collection_name.createIndex({ array_field: 1 }) // multikey
db.collection_name.createIndex({ location: "2dsphere" }) // geospatial
Index types
Indexing an array field creates a multikey index with an entry per element. 2dsphere indexes support geospatial queries, hashed indexes support hashed sharding and equality, TTL indexes delete documents after a time, and partial indexes cover only documents matching a filter.
Wildcard indexes cover unpredictable field names.
Note:
Partial indexes are smaller and faster when you only query a subset.
Example: Index types
test> db.posts.createIndex({ tags: 1 }) // multikey
test> db.places.createIndex({ location: "2dsphere" }) // geospatial
test> db.logs.createIndex({ at: 1 }, { expireAfterSeconds: 86400 }) // TTL: one day
test> db.users.createIndex({ email: 1 }, { partialFilterExpression: { active: true }, unique: true })
test> db.users.createIndex({ "$**": 1 }) // wildcard
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using the wrong type for the query
- Forgetting TTL indexes run about once a minute
- Indexing arrays that grow unbounded
Chapter Summary
- Multikey indexes array elements
- 2dsphere for geo queries
- TTL expires documents
- Partial indexes cover a subset
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: