mongodb move documents from one collection to another collection

前端 未结 15 1521
感情败类
感情败类 2020-11-30 22:10

How can documents be moved from one collection to another collection in MongoDB?? For example: I have lot of documents in

15条回答
  •  不思量自难忘°
    2020-11-30 22:50

    I had 2297 collection for 15 million of documents but some collection was empty.

    Using only copyTo the script failed, but with this script optimization:

    db.getCollectionNames().forEach(function(collname) {
        var c = db.getCollection(collname).count();
        if(c!==0){
          db.getCollection(collname).copyTo('master-collection');
          print('Copied collection ' + collname);
        }
    });
    

    all works fine for me.

    NB: copyTo is deprecated because it block the read/write operation: so I think is fine if you know that the database is not usable during this operation.

提交回复
热议问题