Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cách copy collection giữa hai database MongoDB

MongoDB không có lệnh copy collection trực tiếp. Sử dụng forEach() kết hợp getSiblingDB() để copy document sang database khác.

Cú pháp

db.tênCollection.find().forEach(function(doc) {
  db.getSiblingDB('databaseĐích')['tênCollection'].insert(doc);
});

Ví dụ minh họa

  1. Tạo collection trong database test:
    > use test
    > db.copyDemo.insertOne({"User_Id": 101, "UserName": "Larry"});
    > db.copyDemo.insertOne({"User_Id": 102, "UserName": "Maxwell"});
    > db.copyDemo.insertOne({"User_Id": 103, "UserName": "Robert"});
  2. Kiểm tra database sample chưa có collection này:
    > use sample
    > show collections;
  3. Copy từ test sang sample:
    > use test
    > db.copyDemo.find().forEach(function(doc) {
      db.getSiblingDB('sample')['copyDemo'].insert(doc);
    });
  4. Xác nhận:
    > use sample
    > show collections;

    Collection copyDemo hiện có trong database sample.

Lưu ý: Cách này copy cả _id. Nếu cần _id mới, hãy delete doc._id trước khi insert. Với data lớn, cân nhắc mongodump/mongorestore hoặc $out trong aggregation.