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
- 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"}); - Kiểm tra database
samplechưa có collection này:> use sample > show collections;
- Copy từ test sang sample:
> use test > db.copyDemo.find().forEach(function(doc) { db.getSiblingDB('sample')['copyDemo'].insert(doc); }); - Xác nhận:
> use sample > show collections;
Collection
copyDemohiệ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.