MongoDB import/export indexes
I need a tool for rapidly recreating the proper "schema" (such as it is) of MongoDB instances between environments that pre-creates the right DB names, collections, sets collection caps, and creates the indexes for each collection. I do NOT want to copy all of the data between the instances, though. Each env I manage has different data but the DB/collection/caps/indexes are all the same. Is there an easy way to do this, preferably a tool that exports a JSON doc of all the names, caps and indexes that can then be re-imported into a new instance?
After I didn't find any appropriate tool, I dumped the database and restored it without data, so metadata is restored (particularly all the collections are created with apropriate indexes), but the collections are empty. This also can be applied to databases with data as well, so the indexes will be created on existing db if there is no conflict.
1.Make a dump with mongodump
2.Empty the data of collections
find ./dump -name '*bson' -type f -exec cp /dev/null {} ;
3.Restore the data to new db with mongorestore
Once, I had the same problem too. What I did is a set of JS files which I had to run manually on each env ( mongo
can evaluate scripts). Those files had data inside so I had to manage them carefully not to introduce dups / corrupt existing data.
But then, I've found migration tools very helpful for such tasks. This one is my favorite, but there are many other solutions.
Think of you changes as of stream of immutable events. Eg: in order to drop previously created index you create new change (migration), which drops it. You store that stream as a set of files right in your VCS, so the setup for new environment is pretty easy ( mm migrate
and your base is up-to-date!) for new folks on a project. Also, this approach is very helpful when you work with containers or VMs: usually, you can trigger a script, based on container / VM life cycle, and thus populate the DB automatically, making restarts / recreations painless.
上一篇: 手动添加动画元素
下一篇: MongoDB导入/导出索引