mongodb how to mongodump only indexes to another mongodb instance

杀马特。学长 韩版系。学妹 提交于 2019-12-04 18:50:40

问题


I have a mongodb instance with a lot of data, now I need to start up a new instance with the same structure without data.

how to get it done?


回答1:


You can do that with the "query" option, with a query that does not return any document. Something like:

mongodump -q '{ "foo" : "bar"  }'

This will dump all the dbs and indexes, you can then do a mongorestore to recreate them into another mongod instance

See documentation: http://docs.mongodb.org/manual/reference/program/mongodump/#cmdoption--query




回答2:


You can login into mongo shell and execute the following code statements to generate creating indexes statements. After that, use the statements to recreate indexes.

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)}");}}


来源:https://stackoverflow.com/questions/26458457/mongodb-how-to-mongodump-only-indexes-to-another-mongodb-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!