0
0
MongodbConceptBeginner · 3 min read

Wildcard Index in MongoDB: What It Is and How It Works

A wildcard index in MongoDB is a special type of index that automatically indexes all fields within documents, including nested fields, without specifying each field name. It helps speed up queries on dynamic or unpredictable document structures by covering many fields with a single index.
⚙️

How It Works

Imagine you have a big box of mixed toys, and you want to quickly find any toy without knowing exactly what kind it is. A wildcard index in MongoDB works like a magic label that tags every toy in the box, no matter its shape or size. Instead of creating separate labels for each toy type, this index covers all toys at once.

Technically, a wildcard index indexes all fields in your documents, including nested objects, by using a special pattern. This means you don't have to guess or list every field you want to search. MongoDB automatically keeps track of all fields, so queries on any field can be faster.

This is especially useful when your data structure changes often or has many different fields, like user profiles with custom attributes or logs with varying details.

💻

Example

This example shows how to create a wildcard index on a collection named products. The index will cover all fields inside each product document.

mongodb
db.products.createIndex({ "$**": 1 })

// Sample query that benefits from the wildcard index
// Find products where any field has the value "blue"
db.products.find({ "$or": [ { "field1": "blue" }, { "field2": "blue" } ] })
Output
{ "acknowledged" : true, "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } // Query output depends on data but runs faster with the wildcard index
🎯

When to Use

Use a wildcard index when your documents have many different or changing fields, and you want to speed up queries without creating many separate indexes. For example:

  • Logging systems where each log entry has different fields.
  • User profiles with custom attributes that vary per user.
  • Applications storing flexible JSON data with unpredictable keys.

However, if your data structure is stable and you know which fields you query often, creating specific indexes on those fields is usually more efficient.

Key Points

  • A wildcard index automatically indexes all fields in documents.
  • It is useful for collections with dynamic or unpredictable fields.
  • Creating a wildcard index is simple with { "$**": 1 }.
  • It can improve query speed but may increase index size.
  • Use it when you cannot predict which fields will be queried.

Key Takeaways

A wildcard index indexes all fields in MongoDB documents automatically.
It is ideal for collections with flexible or changing document structures.
Create it using the special key pattern { "$**": 1 }.
It speeds up queries on any field but may use more storage.
Use specific indexes if your query fields are known and stable.