mongodb如何mongodump只索引到另一个mongodb实例

enz*_*ang 10 mongodb mongodump tokumx

我有一个包含大量数据的mongodb实例,现在我需要启动一个没有数据的相同结构的新实例.

如何完成它?

Tug*_*all 13

您可以使用"查询"选项执行此操作,查询不返回任何文档.就像是:

mongodump -q '{ "foo" : "bar"  }'
Run Code Online (Sandbox Code Playgroud)

这将转储所有dbs和索引,然后您可以执行mongorestore将它们重新创建到另一个mongod实例中

参见文档:http: //docs.mongodb.org/manual/reference/program/mongodump/#cmdoption--query

  • 好技巧.但是,如果你确实有一个没有"foo"索引的大集合,它将非常慢.解决方法是使用始终具有索引的_id:mongodump -q'{"_ id":"bar"}' (6认同)
  • 从 3.6.3 版本开始,这个技巧不太有效。我得到“错误选项:无法使用没有指定集合的​​查询转储”。如果我指定集合,它就可以工作 - 但这当然意味着我必须在开始之前了解所有集合。 (3认同)

小智 7

您可以登录 mongo shell 并执行以下代码语句以生成创建索引语句。之后,使用语句重新创建索引。

var collectionList = db.getCollectionNames();
for(var index in collectionList){
    var collection = collectionList[index];
        var cur = db.getCollection(collection).getIndexes();
        if(cur.length == 1){
            continue;
        }
        for(var index1 in cur){
            var next = cur[index1];
            if(next["name"] == '_id_'){
                continue;
            }
       var unique=next["unique"]?true:false;
       print("try{ db.getCollection(\""+collection+"\").createIndex("+JSON.stringify(next["key"])+",{unique:"+unique+"},{background:1})}catch(e){print(e)}");}}
Run Code Online (Sandbox Code Playgroud)


Ozz*_*ech 6

有一个非常简短而出色的脚本来创建索引查询的备份:

print(`// Backup indexes of : ${db.getName()} : database`);
print(`use ${db.getName()};`);

db.getCollectionNames().forEach(function (collection) {
    indexes = db.getCollection(collection).getIndexes().forEach(function (index) {
        if (index.name === '_id_') return; // skip defalut _id indexes
        const keys = tojsononeline(index.key);
        delete index.id; delete index.key; delete index.v; delete index.ns;
        print(`db.${collection}.createIndex(${keys}, ${tojsononeline(index)});`);
    });
});
Run Code Online (Sandbox Code Playgroud)

您可以直接从 mongo shell 运行它,如下所示:

mongo --quiet mongodb://localhost:27017/mydatabase indexes-backup.js
Run Code Online (Sandbox Code Playgroud)

输出看起来像:

db.user.createIndex({"user.email":1}, {"name":"userEmail", "background":true});
Run Code Online (Sandbox Code Playgroud)