Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb how to mongodump only indexes to another mongodb instance

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?

like image 705
enzoyang Avatar asked Oct 20 '14 04:10

enzoyang


People also ask

Does Mongodump dump indexes?

mongodump excludes the content of the local database in its output. mongodump output only captures the documents in the database and does not include index data. mongorestore or mongod must then rebuild the indexes after restoring data.

What is the difference between Mongodump and Mongoexport?

mongoexport is a command-line tool that produces a JSON or CSV export of data stored in a MongoDB instance. mongodump is a utility for creating a binary export of the contents of a database.

How do I transfer data from one database to another in MongoDB?

To copy a collection, you can clone it on the same database, then move the cloned collection. To clone: > use db1 switched to db db1 > db.


2 Answers

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

like image 56
Tug Grall Avatar answered Sep 21 '22 08:09

Tug Grall


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)}");}}
like image 36
Ivan Chen Avatar answered Sep 21 '22 08:09

Ivan Chen