Eyal Roth
Eyal Roth

Reputation: 4019

MongoDB aggregation: Performance of queries with both indexed and non-indexed fields

Say I have a MongoDB collection of documents with only two fields - x and y - and one of them (say, x) has an index.

Will any of the following queries will have better performance than the other?

Single-match query:

db.collection.aggregate({$match : {x : "value", y : "value"}})

Double-match query (indexed field matched first):

db.collection.aggregate({$match : {x : "value"}}, {$match : {y : "value"}})

Upvotes: 0

Views: 551

Answers (2)

Asya Kamsky
Asya Kamsky

Reputation: 42352

Will any of the following queries will have better performance than the other?

In a nutshell: no. The performance will be more-or-less the same, at least as far as both of them will use the same index.

db.collection.aggregate({$match : {x : "value", y : "value"}})

This will use the index on {x:1} the same way that a regular find() on x and y would use it.

Double-match query (indexed field matched first): db.collection.aggregate({$match : {x : "value"}}, {$match : {y : "value"}})

The first $match will use the index on x just like a find would.

In the first case the index is used to reduce the resultant set of documents to examine for matching y value. In the second case the index is used to only pass through the pipeline the documents that match x so the second state would have to in-memory examine them for whether they match y.

This is basically the same operation in both cases efficiency-wise.

Upvotes: 2

Sammaye
Sammaye

Reputation: 43884

The single match will have better performance since it can use a single index.

The double match is actually treated as a double $match, a.k.a a $match within a $match as such an index is not actually use for the second $match.

This behaviour however, has been changed in 2.5.4: https://jira.mongodb.org/browse/SERVER-11184 so that multiple calls will just result in one call on the server. This is actually a bit of a bummer since it makes some queries that require a second non-indexed part harder now :\.

Upvotes: 0

Related Questions