Wild card index and aggregation pipeline stages

I am using mongo 4.2 version

I have read wild card index and its restrictions WildCard Index restrictions

But still need to know few more points about the restrictions in wild card index
I have created wild card index for the whole document like

“db.collection.createIndex({”$**:1"})
When I tried to check its executionPlan I found the following results

For all aggregate queries having $unwind in that query

  1. Index keys are not examined
  2. Always COLLSCAN is executed

From the above experiment I could observe that for any aggregate queries wild card will not work. Is my understanding correct. If yes can someone explain the above behavior?

Hi @Sowmya_LR,

Wellcome to MongoDB Community.

For aggregations there are specific restrictions. However, if you want the aggregation to use the index you need to perform either a $match or $sort stages in the beginning of the query.

If you are starting your aggregation with the $unwind stage the aggregation will not be able to utilise an index and will unfold everything with collscan and memory operations.

Can you share the aggregation with us?

Thanks,
Pavel

2 Likes

Hi @Pavel_Duchovny

Thank you for the reply. The pipeline stages will be as follows

db.collection.aggregate([
{$unwind: “$Instance”},
{$match:{“Instance.field”:“value”}}
])

Hi @Sowmya_LR,

This pipeline cannot use the index as unwind is first stage.

Why not do the following:

 db.collection.aggregate([{$match:{“Instance.field”:“value”},
{$unwind: “$Instance”},
{$match:{“Instance.field”:“value”}}
])

This will allow the query to first filter on index and then do the rest.

Thanks
Pavel

1 Like