We came across a situation where-in, MongoDB Query was taking more time in Production like 10 seconds and 4.2 seconds but same query performed well in UAT taking under 400 ms.
- The very first thought that was evident to us that it is because of amount of data which differed in UAT and Production.
Then we ran following to see the execution plan -
db.collection.aggregate(<queries>).explain()
- This gave us Winning and Rejected Plans. Under which, we analyzed that although it was using 'IXSCAN.' But, it was incorrect index- as we had one compound index built on time field and other fields, and there was other index just on time field for TTL purposes.
- Winning plan picked TTL index rather than compound index. Thus, we dropped TTL index and built TTL index on a different time field.
- That got our query performance time from 10 seconds to 726 ms.
- Also, for other query the performance came down from 8 seconds to 4.3 seconds.
Then, we ran following -
db.collection.aggregate(<queries>).explain("executionStats")
- This gave us following information -
executionTimeMillis: 5624,
totalKeysExamined: 5837808,
totalDocsExamined: 2,
- Although, query was just returning 2 records but it was examining 5.8 million records despite using index. And thus, it was taking nearly 5.6 seconds.
- And, it was because we were using Regex match like -
{ "macAddress" : { $regex : "^XX:?0X:?XX:?1X:?2X:?E5$(?i)", $options : "i"}}
- So, we decided to change API code and convert regex to in clause query like -
macAddress: {$in:["XX0XXX1X2XE5","xx0xxx1x2xe5","XX:0X:XX:1X:2X:E5","xx:0x:xx:1x:2x:e5"]}
- Using in clause led to bringing down totalKeysExamined.
- Thus, bringing down time from 4.3 seconds to 200 ms
Comments
Post a Comment