Mongo DB is considered to be very fast in its operations, but if it’s your first project and you created an application using MongoDB but it doesn’t run fast or keeps on crashing then it’s time to go back and check if you’re doing it correctly. Given below are some steps you should do in order to troubleshoot your application and make it faster.
- Running the queries and checking their response time individually. If any query is taking more than 2 seconds, then we should optimize it
- By default MongoDB records all queries that take longer than 100 millisecond. It’s located at /var/log/mongodb/mongod.log
- Checking for unnecessary looping inside the code of NodeJS
- You can add explain(‘executionStats’) to a query
- user.find(
- { country: ‘AU’, city: ‘Melbourne’ }
- )
- This would return a large JSON result but 2 values have to be examined
- nReturned — the number of documents returned, and
- totalDocsExamined — the number of documents scanned to find the result.
- If the number of documents examined greatly exceeds the number returned, the query may not be efficient. In the worst cases, MongoDB might have to scan every document in the collection. The query would therefore benefit from the use of an index.
- By Addding Indexes. By adding index mongodb scans for only through the index without having to scan the entire collection
- user.createIndex({ country: 1 });
- user.createIndex({ country: 1, city: 1 });
- For Sorting,add an index of the same kind before
- If sorting has to be done in this order
- user.find().sort({ country: 1, city: 1 });
- There should also be an index of the same kind
- user.createIndex({ country: 1, city: 1 });
- This would also work if both are in reverse order
- user.find().sort({ country: -1, city: -1 });
- However if one is in ascending order and the other is descending, then another index of the same kind has to be created
- If sorting has to be done in this order
- Creating two or more connection objects would optimize the performance. If you have a complex query which takes ten seconds to run, no one else can interact your application at the same time on the same connection. Performance can be improved by defining more than one database connection object. For example:
- one to handle the majority of fast queries
- one to handle slower document inserts and updates
- one to handle complex report generation.
Each object is treated as a separate database client and will not delay the processing of others. The application should remain responsive.
- Setting Maximum execution time using maxTimeMS(). By using this a slowly executing query would not hold up other queries
- repairDatabase can be used to repair the database as a last resort if everything else fails