Raz Buchnik
Raz Buchnik

Reputation: 8401

MongoDB indexes are not working when querying with $facet

I have index on the status key in the example collection. This is the aggregate query I make:

db.getCollection('example').aggregate([
    {
        $facet: {
            Active: [
                {
                    $match: {
    
                            status: "OK"
                    }
                }
            ]
       }
   }
])

this query takes above to 10s to return. If I do the same query using find, instead of aggregate, the query will return in 0.003 ms. As I mentioned there is index on status key.

What am I missing in here?

Upvotes: 1

Views: 802

Answers (1)

Joe
Joe

Reputation: 28316

A MongoDB aggregation operates as a pipeline, documents are read from the named collection at the start of the pipeline, matched and/or mutated as by each stage, and then passed along to the next stage.

A $facet stage, every document that is passed to the stage is forwarded to each facet.

In the case of your pipeline, the aggregation will read all of the documents from the collection, and pass them in their entirety to the Active facet where the $match stage will dutifully examine each one.

When the aggregation pipeline begins with a stage that filters, like $match or $geoNear, it will use an index to select matching documents from the collection, greatly reducing the number of documents that enter the pipeline.

Upvotes: 1

Related Questions