$match with $facet - Index usage

Hi Team,

Kindly confirm if the below understanding is correct,
$match (as first stage) followed by $facet will use indexes based on the fields mentioned in $match pipeline.

Regards,
Rama

It should. And it did in the following example using sample_training.zips collection of the Atlas sample data sets.

// I first created an index on the state field:
mongosh> c.getIndexes()
[ { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { state: 1 }, name: 'state_1', background: false } ]
// I will match on Alabama
mongosh> match = { "$match" : { "state" : "AL" } }
// To first count the number of zips
mongosh> count_zips = [ { "$group" : { "_id" : null , "count" : { "$sum" : 1 } } } ]
// And the total population
mongosh> count_pop = [ { "$group" : { "_id" : null , "pop" : { "$sum" : "$pop" } } } ]
// Using a facets
mongosh> facets = { "$facet" : { count_zips , count_pop } }
// Testing the pipeline
mongosh> p = [ match , facets ]
mongosh> c.aggregate( p )
// Which gives the result
[ { count_zips: [ { _id: null, count: 567 } ],
    count_pop: [ { _id: null, pop: 4040587 } ] } ]
// Verified if my index was used with
mongosh> c.aggregate( p ).explain()
3 Likes

Thanks for the confirmation

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.