MongoDB에서 컬렉션 복제하기
MongoDB에서 컬렉션을 복제(clone)하려면 forEach() 메서드를 활용하면 됩니다. 이 메서드는 원본 컬렉션의 모든 문서를 순회하면서 각 문서를 새로운 컬렉션에 삽입하는 방식으로 동작합니다.
먼저 예제로 사용할 문서가 포함된 컬렉션을 생성해 보겠습니다.
1. 샘플 컬렉션 생성
다음 쿼리를 사용하여 문서가 담긴 컬렉션을 생성할 수 있습니다.
> 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")
}위 쿼리는 studentInformation 컬렉션에 세 개의 학생 문서(Chris, Robert, James)를 차례대로 삽입합니다.
2. 삽입된 문서 확인
find() 메서드를 사용하면 컬렉션의 모든 문서를 조회할 수 있습니다.
> db.studentInformation.find().pretty();
실행 결과는 다음과 같습니다.
{ "_id" : ObjectId("5c8bc15780f10143d8431e21"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c8bc15e80f10143d8431e22"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5c8bc17380f10143d8431e23"), "StudentName" : "James" }3. 컬렉션 복제 실행
이제 MongoDB에서 컬렉션을 복제하는 핵심 쿼리입니다. forEach() 메서드 안에서 각 문서를 새 컬렉션에 삽입하는 함수를 정의합니다.
> db.studentInformation.find().forEach( function(copyValue){db.makingStudentInformationClone.insert(copyValue)} );이 쿼리는 studentInformation 컬렉션의 모든 문서를 하나씩 읽어 makingStudentInformationClone이라는 새 컬렉션에 그대로 복사합니다. 대상 컬렉션이 존재하지 않으면 MongoDB가 자동으로 생성해 주므로 별도의 생성 과정이 필요하지 않습니다.
4. 복제된 컬렉션 확인
복제가 정상적으로 완료되었는지 확인해 보겠습니다.
> db.makingStudentInformationClone.find();
실행 결과는 다음과 같습니다.
{ "_id" : ObjectId("5c8bc15780f10143d8431e21"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c8bc15e80f10143d8431e22"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5c8bc17380f10143d8431e23"), "StudentName" : "James" }원본 컬렉션과 동일한 문서들이 복제된 것을 확인할 수 있습니다. ObjectId까지 함께 복사되기 때문에 원본과 완전히 동일한 데이터가 유지됩니다.
5. 전체 컬렉션 목록에서 복제본 확인
마지막으로 복제된 컬렉션을 포함한 전체 컬렉션 목록을 조회해 보겠습니다.
> show collections;
실행 결과는 다음과 같습니다.
copyThisCollectionToSampleDatabaseDemo deleteDocuments deleteDocumentsDemo deleteSomeInformation employee getElementWithMaxIdDemo internalArraySizeDemo makingStudentInformationClone prettyDemo selectWhereInDemo sourceCollection studentInformation updateInformation userInformation
목록에서 makingStudentInformationClone이 추가된 것을 확인할 수 있습니다. 이처럼 forEach() 메서드를 활용하면 별도의 도구 없이 몽고 셸(mongo shell)만으로 손쉽게 컬렉션을 복제할 수 있습니다.