如何在 mongodump 上转储多个集合或排除集合?mongodb 是 2.6 版
我现在就是这样做的。
mongodump --collection map_accounts_clicks --out /dumps
Run Code Online (Sandbox Code Playgroud)
由于 --excludeCollection 是在 mongo 3.0 中引入的,并且 --collection 是一个只能提交一次的参数,因此没有官方的方法可以做到这一点。
您可以做的是在之前查询 mongo 以获取所有想要的集合作为数组,然后循环遍历该数组以转储每个集合:
首先,让我们看看您的 bash 脚本。它将调用 mongo 客户端来接收与给定搜索词匹配的集合列表:
database_name="database1" # target database
searchTerm="foobar" # if you do not want to dump all collections
strCollections=$(mongo localhost:27017/${database_name} getCollections.js --eval "var searchTerm = ${searchTerm}")
Run Code Online (Sandbox Code Playgroud)
引用的java脚本文件如下所示:
{
// remember to set slaveOk if you working on a replica set and query a slave
// rs.slaveOk();
// init your result array
var wantedCollections = [];
// first get all existing collections
var collections = db.getCollectionNames();
// count number of existing collections
var collectionsCount = collections.length;
// prepare your regular expression, searchTerm is a variable coming from the command line
var regEx = new RegExp(searchTerm, 'g');
// now loop through all existing collections
for (var i = 0; i < collectionsCount; i++) {
// check if search term matches collection name
var regExMatch = regEx.test(collections[i]);
// if so, add it to our result array
if (regExMatch == true) {
wantedCollections.push(collections[i]);
}
}
// finally print result array, it's a comma separated list, perfect to work with in bash
print(wantedCollections);
}
Run Code Online (Sandbox Code Playgroud)
回到你的 bash 脚本。现在我们有了要导出的集合列表。首先,您需要将逗号分隔的集合列表转换为数组:
IFS=', ' read -r -a collections <<< "$strCollections"
Run Code Online (Sandbox Code Playgroud)
现在,您只需循环遍历数组中的集合并像往常一样转储它们:
for collection in "${collections[@]}"
do
mongodump \
--db=${database_name} \
--collection ${collection} \
--out ${destination_folder}
done
Run Code Online (Sandbox Code Playgroud)
就这样。缺点是:如果为每个单个集合运行 mongodump,则无法利用并行导出。对此也有一个解决方法。但这再次要求您使用 --exclude-collection。
| 归档时间: |
|
| 查看次数: |
6673 次 |
| 最近记录: |