How to create MongoDB backups on Java

kommradHomer
Nov 9, 2020

Creating backups and restoring them via mongodump and mongorestore binaries is pretty easy and straightforward . But what If you need to do so programmatically, simultaneously, for hundreds of times every hour, for creating different views or partitions of that DB? You should be doing some coding and the ProcessBuilder API in Java8 is your friend!

You can use mongodump and mongorestore from within your Java code by using ProcessBuilder to make system calls conveniently , and easily reading the standard and error outputs. ProcessBuilder actually helps us with creating and managing a process, with many customization options available.

Below is a class, with comments next to every optional argument to the shell command. The example showcases a java code run on Ubuntu 20.04. I’m pretty sure that you will have no problem with any recent version of Ubuntu and Java8+

The less obvious thing is to provide every piece of argument String in a list , seperately. You should not use any spaces or whitespaces at all. Otherwise, you will keep getting argument errors like positional arguments not allowed.

The most useful aspect of using mongodump via Java should be providing a different query for various scenarios. That is how you can create different dumps of same DB and partition the data, say , for each user or account or such department. I’m not sure If you can use aggregation but all the valid queries must be acceptable to mongodump.

--

--

kommradHomer

proud seeder of 146.5GB The.Lord.of.the.Rings.Trilogy.1080p.Extended.Complete.Bluray.DTS-HD-6.1.x264-Grym