Để clone (sao chép) một collection trong MongoDB, bạn có thể sử dụng phương thức forEach() kết hợp với insert().
Cú pháp
db.sourceCollection.find().forEach(
function(doc) { db.targetCollection.insert(doc); }
);
Ví dụ minh họa
Tạo collection nguồn và dữ liệu
> db.studentInformation.insertOne({"StudentName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8bc15780f10143d8431e21") }
> db.studentInformation.insertOne({"StudentName":"Robert"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8bc15e80f10143d8431e22") }
> db.studentInformation.insertOne({"StudentName":"James"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8bc17380f10143d8431e23") }
Xem dữ liệu nguồn
> db.studentInformation.find().pretty();
{
"_id" : ObjectId("5c8bc15780f10143d8431e21"),
"StudentName" : "Chris"
}
{
"_id" : ObjectId("5c8bc15e80f10143d8431e22"),
"StudentName" : "Robert"
}
{
"_id" : ObjectId("5c8bc17380f10143d8431e23"),
"StudentName" : "James"
}
Thực hiện clone
> db.studentInformation.find().forEach(
function(copyValue) { db.makingStudentInformationClone.insert(copyValue) }
);
Kiểm tra collection clone
> db.makingStudentInformationClone.find();
{
"_id" : ObjectId("5c8bc15780f10143d8431e21"),
"StudentName" : "Chris"
}
{
"_id" : ObjectId("5c8bc15e80f10143d8431e22"),
"StudentName" : "Robert"
}
{
"_id" : ObjectId("5c8bc17380f10143d8431e23"),
"StudentName" : "James"
}
Xác nhận cả 2 collection tồn tại
> show collections;
studentInformation makingStudentInformationClone ... (các collection khác)
Lưu ý quan trọng
- _id được giữ nguyên: Clone này copy y compris _id. Nếu insert vào cùng database, sẽ trùng _id nếu chạy lần 2.
- Cách tránh trùng _id: Loại bỏ _id trước khi insert:
db.source.find().forEach(function(doc) { delete doc._id; db.target.insert(doc); }); - Hiệu năng: Với collection lớn, dùng
mongoexport/mongoimporthoặc aggregation$outnhanh hơn.
Cách hiện đại (MongoDB 4.2+): Aggregation $merge
db.sourceCollection.aggregate([
{ $match: {} },
{ $merge: { into: "targetCollection", whenMatched: "replace", whenNotMatched: "insert" } }
]);
Cách nhanh nhất: mongoexport/mongoimport
# Export mongoexport -d mydb -c sourceCollection -o data.json # Import mongoimport -d mydb -c targetCollection --file data.json