Computer >> Máy Tính >  >> Lập trình >> MongoDB

Sao chép một bộ sưu tập trong MongoDB?


Để sao chép một bộ sưu tập trong MongoDB, bạn có thể sử dụng phương thức forEach (). Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với một tài liệu.

Truy vấn để tạo một bộ sưu tập với một tài liệu như sau -

> db.studentInformation.insertOne ({"StudentName":"Chris"}); {"nition ":true," insertId ":ObjectId (" 5c8bc15780f10143d8431e21 ")}> db.studentInformation.insertOne ({" StudentName " :"Robert"}); {"inherit":true, "insertId":ObjectId ("5c8bc15e80f10143d8431e22")}> db.studentInformation.insertOne ({"StudentName":"James"}); {"Recognition":true, "insertId":ObjectId ("5c8bc17380f10143d8431e23")} 

Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau -

> db.studentInformation.find (). pretty (); 

Sau đây là kết quả -

 {"_id":ObjectId ("5c8bc15780f10143d8431e21"), "StudentName":"Chris"} {"_id":ObjectId ("5c8bc15e80f10143d8431e22"), "StudentName":"Robert"} {"_id":ObjectId ( "5c8bc17380f10143d8431e23"), "StudentName":"James"} 

Đây là truy vấn để tạo bản sao trong MongoDB -

> db.studentInformation.find (). forEach (function (copyValue) {db.makingStudentInformationClone.insert (copyValue)}); 

Hãy để chúng tôi kiểm tra các tài liệu của bộ sưu tập nhân bản trong MongoDB. Truy vấn như sau -

> db.makingStudentInformationClone.find (); 

Sau đây là kết quả -

 {"_id":ObjectId ("5c8bc15780f10143d8431e21"), "StudentName":"Chris"} {"_id":ObjectId ("5c8bc15e80f10143d8431e22"), "StudentName":"Robert"} {"_id":ObjectId ( "5c8bc17380f10143d8431e23"), "StudentName":"James"} 

Bây giờ chúng ta hãy kiểm tra danh sách tất cả các bộ sưu tập bao gồm cả bản sao. Truy vấn như sau -

> hiển thị bộ sưu tập; 

Sau đây là kết quả -

 copyThisCollectionToSampleDatabaseDemodeleteDocumentsdeleteDocumentsDemodeleteSomeInformationenitioneegetElementWithMaxIdDemointernalArraySizeDemomakingStudentInformationCloneprettyDemoselectWhereInDemosourceCollectionstudentInformationupdemosourceCollectionstudentInformation