← Back to MongoDB Course | Chapter 8: Indexes | Lesson 5 of 7

Index types

Besides ordinary indexes MongoDB offers multikey, text, geospatial, hashed, TTL, partial and wildcard indexes.

In this page:

  1. Index types
Syntax
javascript
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

bash
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
  1. Using the wrong type for the query
  2. Forgetting TTL indexes run about once a minute
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.