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

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

Is there a simple way to do this?

相关标签:
19条回答
  • 2020-11-28 00:56

    for huge size collections, you can use Bulk.insert()

    var bulk = db.getSiblingDB(dbName)[targetCollectionName].initializeUnorderedBulkOp();
    db.getCollection(sourceCollectionName).find().forEach(function (d) {
        bulk.insert(d);
    });
    bulk.execute();
    

    This will save a lot of time. In my case, I'm copying collection with 1219 documents: iter vs Bulk (67 secs vs 3 secs)

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 01:01

    I'd usually do:

    use sourcedatabase;
    var docs=db.sourcetable.find();
    use targetdatabase;
    docs.forEach(function(doc) { db.targettable.insert(doc); });
    
    0 讨论(0)
  • 2020-11-28 01:02

    This might be just a special case, but for a collection of 100k documents with two random string fields (length is 15-20 chars), using a dumb mapreduce is almost twice as fast as find-insert/copyTo:

    db.coll.mapReduce(function() { emit(this._id, this); }, function(k,vs) { return vs[0]; }, { out : "coll2" })
    
    0 讨论(0)
  • 2020-11-28 01:03

    I know this question has been answered however I personally would not do @JasonMcCays answer due to the fact that cursors stream and this could cause an infinite cursor loop if the collection is still being used. Instead I would use a snapshot():

    http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database

    @bens answer is also a good one and works well for hot backups of collections not only that but mongorestore does not need to share the same mongod.

    0 讨论(0)
  • 2020-11-28 01:03

    This won't solve your problem but the mongodb shell has a copyTo method that copies a collection into another one in the same database:

    db.mycoll.copyTo('my_other_collection');
    

    It also translates from BSON to JSON, so mongodump/mongorestore are the best way to go, as others have said.

    0 讨论(0)
提交回复
热议问题