Managing MongoDB Bulk Deletes and Inserts

MongoDB bulk deletes and insertsIn this blog post, we’ll look at how to manage MongoDB bulk deletes and inserts with little impact on production traffic.

If you are like me, there is no end to the demands placed on you as a DBA. One of the biggest is when we want to load X% more data into the database, during peak traffic no less. I refer to this as MongoDB bulk deletes and inserts. As a DBA, my first reaction is “no, do this during off-peak hours.” However, the business person in me says what if this is due to clients loading a customer, product, or email list into the system for work during business hours. That puts it into another light, does it not?

This raises the question of how can we change data in the database as fast as possible while also trying to give the production system some breathing room. In this blog, I wanted to give you some nice scripts that you can load into your MongoDB shell to really simplify the process.

First, we will cover an iterative delete function that can be stopped and restarted at any time. Next, I will talk about smart updating with similarly planned overhead. Lastly, I want to talk about more advanced forms of health checking when you want to do something a bit smarter than where this basic series of scripts stop.

MongoDB Bulk Deletes with a Plan

In this code, you can see there are a couple of ways to manage these deletes. Specifically, you can see how to call this from anywhere (deleteFromCollection). I’ve also shown how to extend the shell so you can call (db.collection.deleteBulk). This avoids the need to provide the namespace, as it can discover that from the context of the function.

The idea behind this function is pretty straightforward: you provide it with a find pattern for what you want to delete. This could be { } if you don’t want to restrict it, but you should use .drop() in that case. After that, it expects a batch size, which is the number of document ID’s to use to drop in a single go. There is a trade-off between more deletes with more iterations or more with fewer iterations. Keep in mind this means there are 1000 of oplog entries per batch (also in my examples). You should consider this carefully and watch your oplog range as a result. You could improve this to allow someone to check that size, but it requires more permissions (we’ll leave that discussion for another time). Finally, between batches, the pauseNS sleeps for that duration.

If you find that the overhead is too much for you, simply kill the shell running this and it will stop running. You can then reduce the batch, increase the pause, or both, to make the system handle the change better. Sadly, this is not an exact science as some people have different behaviors they consider an “acceptable” from an impact perspective with so many writes. We will talk about this more in a bit:

MongoDB Bulk Inserts With a Plan

Not to be outdone with the deletes, MongoDB updates and inserts are equally good for the same logic. In these cases, only small changes would be needed to create batches of inserts and then pass .insert(batchBucket) into the shell. Using “sleep” allows breather room for other reads and actions in the system. I find we don’t need this for modern MongoDB using WiredTiger, but your mileage can vary based on workloads. Also, you might want to figure out a way to tell the script how to handle a document that already exists. In the case of data loading, you could wrap the script with a check for errors not including a duplicate key. Please note it’s very easy to duplicate data if you do not have a unique index, and MongoDB is auto assigning its own _id field.

Updates are a tad tricker as they can be expensive if the query portion of the code is not indexed. I’ve provided you with an example, however. You should consider the query time when planning batches and pauses — the more the update is based on a table scan, the smaller the batch you should consider. The reasoning here is that we want to avoid restarting and causing a new table scan as much as possible. A future improvement might be to also support reads from a secondary, and doing the update itself on the primary by the _id field, to ensure a pin-pointed update query.

In each iteration, the update prints out the failure. You can extend this example code to either write the failures to a file or try to automatically fix any issues as appropriate. My goal here is to provide you the starter function to build on. As with the earlier example, this assumes the JS shell, but you can follow the logic in the programming language of your choice if you would rather use Python, Golang or Java.

If you got nothing else from this blog on MongoDB bulk deletes and inserts, I hope you learned a good deal more about writing functions in the shell. Hopefully, you learned how to use programming to add pauses to the bulk operations you need to do. Taking this forward, you could be inventive by having a query to measure latency to trigger pauses (canary query), or even measure things like the oplog to ensure your not adversely impacting HA and replication. There is no right answer, but this is a great start towards explaining more operationally safe ways to do the bigger actions DBAs are asked to do from time to time.

You May Also Like

MongoDB is one of the fastest growing database technologies today. Developers prefer MongoDB because of its flexibility and power, which allows them to build extremely high-performance apps. In Why Developers Prefer MongoDB, we discuss each of MongoDB’s advantages and when they make the best business sense.

Become a MongoDB® Replica Set Expert in Under 5 Minutes outlines a prudent way to run a MongoDB replica set for read scaling in production. The brief also covers advanced features that will empower you to use a best practice architecture right from the start. Download the brief to learn more.

Share this post