从Mongo 3.2迁移到Mongo 3.4时迁移带有额外键的索引。
从Mongo 3.2迁移到Mongo 3.4时迁移带有额外键的索引。
我遇到了与这个问题相同的问题:
MongoDB从3.2转储,使用3.4还原,错误索引保存= null
在我的情况下,手动重新创建索引不是一个选择,我需要一个脚本来自动化此过程,以便稍后迁移我的生产环境。
我尝试过的方法:
1/ 在新数据库的mongo shell中运行以下代码:
for (var collection in ["_tempstore", "contracts", "images", "thumbs", "covers", "invoices"]) { db.getCollection("cfs_gridfs." + collection + ".files").createIndex({filename: 1}); db.getCollection("cfs_gridfs." + collection + ".chunks").createIndex({files_id: 1, n: 1}); }
但是失败了。
2/ 通过运行以下代码,摆脱旧数据库中索引上的多余w
键,这是问题的根源:
db.system.indexes.update({w: {$exists: true}}, {$unset: {w: ""}})
但是这也失败了。
正确的操作方法是什么?
问题:如何将Mongo 3.2中具有额外键的索引迁移到Mongo 3.4?
原因:在MongoDB 3.4中,索引的格式发生了变化,包括了额外的键。因此,如果从Mongo 3.2迁移到Mongo 3.4,之前创建的索引可能会造成问题。
解决方法:
1. 创建两个文件:sanitize.sh和remove-extraneous-keys-from-indexes.js。
2. 在sanitize.sh文件中,使用bash脚本编写以下内容:
#!/usr/bin/env bash DUMP_PATH=$1 for file in $( ls $DUMP_PATH | grep .*\.metadata\.json ); do node remove-extraneous-keys-from-indexes.js $DUMP_PATH/$file done
3. 在remove-extraneous-keys-from-indexes.js文件中,使用Node.js编写以下内容:
const fs = require("fs"); const {promisify} = require("util"); const fileName = process.argv[2]; (async () => { const text = await promisify(fs.readFile)(fileName, 'utf8') const json = JSON.parse(text) json.indexes = json.indexes.map(index => ({ v: index.v, key: index.key, name: index.name, ns: index.ns })) await promisify(fs.writeFile)(fileName, JSON.stringify(json)) })()
4. 授予sanitize.sh文件执行权限:
$ chmod u+x sanitize.sh
5. 运行sanitize.sh脚本并指定Mongo备份文件夹的路径:
$ ./sanitize.sh path/to/dump/folder
6. 最后,运行mongorestore命令进行恢复操作。
注意:此脚本假设您已经安装了最新版本的Node.js。您可以通过运行`node -v`命令来检查Node.js的版本,应该是8.6或更高版本。