Intermediate LevelMongoDB & Mongoose
How do Wildcard Indexes index unpredictable dynamic subdocument fields?
❓ Interview Prompt: Explain Wildcard Indexes ($**), indexing arbitrary dynamic subdocuments, key-value search, and memory trade-offs.
Wildcard Indexes ('$**') allow indexing arbitrary, unknown, or dynamic key-value pairs inside nested subdocument attributes without creating explicit individual compound indexes:
Use Case:
E-commerce products with dynamic user-defined attributes (e.g. 'attributes.color', 'attributes.screenSize').
Code Implementation Example
typescript
import { Schema } from 'mongoose';
const productSchema = new Schema({
name: String,
attributes: Schema.Types.Mixed // Dynamic dynamic key-value pairs
});
// Index ALL fields inside attributes subdocument!
productSchema.index({ 'attributes.$**': 1 });💡Defining a Wildcard Index over dynamic subdocument attributes.
🎯 Interview Key Takeaway
Create Wildcard Indexes ($**) to support queries against unpredictable user-defined dynamic attributes.
#Wildcard Index#$**#Dynamic Schema#Intermediate
Back to all MongoDB & Mongoose Questions→