MongoDB Import / Export Indices

I need a tool to quickly recreate the correct โ€œschemaโ€ (such as it) of MongoDB instances between environments that pre-create the correct database names, collections, collection sets and create indexes for each collection. However, I do not want to copy all the data between the instances. Each env that I manage has different data, but DB / collection / caps / index are all the same. Is there an easy way to do this, preferably a tool that exports a JSON document from all names, caps, and indexes, which can then be re-imported into a new instance?

+6
source share
2 answers

After I did not find a suitable tool, I dumped the database and restored it without data, so the metadata is restored (especially all collections are created with the corresponding indexes), but the collections are empty. It can also be applied to data databases, so indexes will be created on the existing db if there is no conflict.

1. Dump with mongodump

2. Run collection data

find ./dump -name '*bson' -type f -exec cp /dev/null {} \;

3. Recover data to new db using mongorestore

+2
source

I once had the same problem. What I did is a set of JS files that I have to run manually on each env ( mongo can evaluate scripts). These files had data inside, so I had to carefully monitor them so as not to introduce duplicate / corrupted existing data.

But then I found the migration tools very useful for such tasks. This one is my favorite, but there are many other solutions .

Think about your changes in relation to the flow of immutable events. For example: to delete a previously created index, you create a new change (migration) that deletes it. You save this stream as a set of files directly in your VCS, so the setup for the new environment is quite simple ( mm migrate and your database is updated!) For new people in the project. In addition, this approach is very useful when working with containers or virtual machines: usually you can run a script based on the container / virtual machine life cycle and thus automatically populate the database, making reboots / carefree painless.

+1
source

Source: https://habr.com/ru/post/989958/


All Articles