Sometimes you may notice that everything in MongoDB is running fine, then you suddenly have performance issues that come up out of nowhere. There can be several reasons why this happens but I am going to cover a few of the common ones here.

  • Long-running queries
  • Index Builds
  • Write contention

MongoDB Slow Queries

Some large queries can take awhile to run but there are some reasons why a query is running long when it shouldn’t be.

Some tools you can use to identify long running queries:

  • Server Logs
    • egrep “[0-9]{3,}ms” mongod.log | awk ‘{ print $NF, $0}’ | grep query | sort -n | tail -n 5
    • egrep “[0-9]{3,}ms” mongod.log | awk ‘{ print $NF, $0}’ | grep orderby | sort -n | tail -n 5
  • db.currentOp()
  • Turning on the profiler
    • db.setProfilingLevel(,)
    • ms is the threshold for logging a query based on the time it took to complete

Once you have identified the query, you can determine if it’s doing a collection scan, if it has a poorly anchored regex or your index is just inefficient.

Index Builds

Index builds can block write operations on your database, so you don’t want to build indexes in the foreground on large tables during peak usage. You can use the background creation of indexes by specifying background: true when creating.

db.collection.createIndex({ a:1 }, { background: true })

This will ultimately take longer to complete, but it will not block operations and will have less of an impact on performance.

Write Contention

If several writers are attempting to update a document, you can run into an issue where writers are competing for locks on the database. You can check the lock status to see if there is an issue by using these commands:

These commands can be used inside the MongoDB Shell:

  • db.serverStatus()
  • db.currentOp()

These commands can be run straight from the command line:

  • Mongotop
  • Mongostat

These will provide insight into the amount of lock contention in your MongoDB instance. You can read more about write contention and concurrency in the Mongo Docs or get help from our experts.

Share This