How to copy a collection from one database to another in MongoDB

前端 未结 19 1604
無奈伤痛
無奈伤痛 2020-11-28 00:22

Is there a simple way to do this?

19条回答
  •  甜味超标
    2020-11-28 00:59

    Actually, there is a command to move a collection from one database to another. It's just not called "move" or "copy".

    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.source_collection.find().forEach(
          function(x){
              db.collection_copy.insert(x)
          }
      );
    

    To move:

    > use admin
    switched to db admin
    
    > db.runCommand(
          {
              renameCollection: 'db1.source_collection',
              to              : 'db2.target_collection'
          }
      );
    

    The other answers are better for copying the collection, but this is especially useful if you're looking to move it.

提交回复
热议问题