简体   繁体   中英

alternate mongo aggregate query

I have an aggregate mongodb query

db.collection.aggregate([
    {$match: {a: "a1", b: "b1"}},{$group: {...}}, 
    {$sort: {...}}, {$limit: {10}}
])

I have a compound index on a and b, and the query is fast.

However when I change the match to

 $match: {$or: [{a: "a1", b: "b1"}, {a: "a2", b: "b2"}]}

the query becomes quite slow and it doesn't seem to use any indices.

Is there any way to either 1) Rewrite the query to use the compound index (as a single query) or 2) Force it to use the index?

I would try adding a sort step to the beginning of the aggregation to see if it forces the use of your index.

db.collection.aggregate([
    {$sort: {a:1, b:1}},
    {$match: {$or: [{a: "a1", b: "b1"}, {a: "a2", b: "b2"}]}},
    ...
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM