简体   繁体   English

mongodb一次导入多个集合

[英]mongodb import multiple collections at once

I am using this command我正在使用这个命令

mongoimport --db databasename mongoimport --db 数据库名

to import a database that I exported using mongoexport.导入我使用 mongoexport 导出的数据库。 The database has over 100 collections in the mongoimport documentation you need to specify the collection name and json file.该数据库在 mongoimport 文档中有 100 多个集合,您需要指定集合名称和 json 文件。 How do I go about importing all the collections at once without having to type a command for each collection如何一次导入所有集合而不必为每个集合键入命令

If dump files are in .json you can use the script for import如果转储文件在 .json 中,您可以使用脚本进行导入

ls *.json | sed 's/.metadata.json//' | while read col; do mongoimport -d db_name -c $col < $col.metadata.json; done

If dump files are in .json.gz you can use the script for import如果转储文件在 .json.gz 中,您可以使用脚本进行导入

ls *.gz | sed 's/.metadata.json.gz//' | while read col; do mongoimport -d db_name --gzip -c $col < $col.metadata.json.gz; done

According to the documentation根据文档

New in version 2.6: If you do not specify --collection, mongoimport takes the collection name from the input filename. 2.6 新版功能:如果您不指定 --collection,mongoimport 将从输入文件名中获取集合名称。 MongoDB omits the extension of the file from the collection name, if the input file has an extension.如果输入文件有扩展名,MongoDB 会从集合名称中省略文件的扩展名。

So it seems it is supposed to do import one collection at a time.所以它似乎应该一次导入一个集合。 So unless you write a shell script to do it, I don't see a way.因此,除非您编写一个 shell 脚本来执行此操作,否则我看不到任何方法。

mongodump and mongorestore are much better for taking full db dump and restore it at once as the other part of the same document says mongodump 和 mongorestore 更适合进行完整的数据库转储并立即恢复它,正如同一文档的其他部分所说

Warning警告

Avoid using mongoimport and mongoexport for full instance production backups.避免使用 mongoimport 和 mongoexport 进行完整实例生产备份。 They do not reliably preserve all rich BSON data types, because JSON can only represent a subset of the types supported by BSON.它们不能可靠地保留所有丰富的 BSON 数据类型,因为 JSON 只能表示 BSON 支持的类型的一个子集。 Use mongodump and mongorestore as described in MongoDB Backup Methods for this kind of functionality.使用 mongodump 和 mongorestore 如 MongoDB 备份方法中所述来实现此类功能。

It is very surprising that there isn't easy to find documentation on importing multiple collections.很难找到有关导入多个集合的文档,这非常令人惊讶。 Restoring a database isn't always intuitive keyword when you are searching for it, but that is what you want to do when you want to restore a database from a backup.当您搜索数据库时,恢复数据库并不总是一个直观的关键字,但当您想从备份恢复数据库时,这就是您想要做的。 If you already have a dump of collections that you exported with mongodump , you should be able to use mongorestore .如果您已经有使用mongodump导出的集合转储,则应该能够使用mongorestore

This is all you really need to run:这就是你真正需要运行的:

mongorestore --db db_name ./db_dumpfiles/

一个简单的命令

mongorestore --db folder_name ./folder_name/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM