Unreasonably slow MongoDB query, even though the query is simple and aligned to indexes

后端 未结 3 655
迷失自我
迷失自我 2021-02-04 10:50

I\'m running a MongoDB server (that\'s literally all it has running). The server has 64gb of RAM and 16 cores, plus 2TB of hard drive space to work with.

The Doc

相关标签:
3条回答
  • 2021-02-04 11:18

    Have you tried adding _id to your composite index. As you're using it as part of the query won't it still have to do a full table scan?

    0 讨论(0)
  • 2021-02-04 11:26

    Bumped into a very similar problem, and the Indexing Advice and FAQ on Mongodb.org says, quote:

    The range query must also be the last column in an index

    So if you have the keys a,b and c and run db.ensureIndex({a:1, b:1, c:1}), these are the "guidelines" in order use the index as much as possible:

    Good:

    • find(a=1,b>2)

    • find(a>1 and a<10)

    • find(a>1 and a<10).sort(a)

    Bad:

    • find(a>1, b=2)

    Only use a range query OR sort on one column. Good:

    • find(a=1,b=2).sort(c)

    • find(a=1,b>2)

    • find(a=1,b>2 and b<4)

    • find(a=1,b>2).sort(b)

    Bad:

    • find(a>1,b>2)

    • find(a=1,b>2).sort(c)

    Hope it helps!

    /J

    0 讨论(0)
  • 2021-02-04 11:30

    Ok I solved it. The culprit was "scanAndOrder": true, which suggested that the index wasn't being used as intended. The correct composite index has the the primary sort field first and then the fields being queried on.

    { "_id":1, "LastUpdated":1 }
    
    0 讨论(0)
提交回复
热议问题