MongoDB에서는 use 명령어를 사용해 손쉽게 데이터베이스 간 전환이 가능합니다. 이 글에서는 "test" 데이터베이스의 컬렉션에 저장된 레코드를 "sample"이라는 이름의 다른 데이터베이스로 옮기는 과정을 단계별로 살펴보겠습니다.
1단계: 컬렉션 생성 및 문서 삽입
먼저 이해를 돕기 위해 문서가 포함된 컬렉션을 하나 만들어 보겠습니다. insertOne() 메서드를 사용하면 컬렉션에 문서를 하나씩 삽입할 수 있습니다.
> db.insertOneRecordDemo.insertOne({"UserName":"Larry","UserAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9534de16f542d757e2b452")
}
> db.insertOneRecordDemo.insertOne({"UserName":"Chris","UserAge":26});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9534e816f542d757e2b453")
}
> db.insertOneRecordDemo.insertOne({"UserName":"David","UserAge":25});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9534f116f542d757e2b454")
}위 쿼리를 실행하면 insertOneRecordDemo라는 컬렉션이 자동으로 생성되고, 세 개의 문서가 순차적으로 삽입됩니다.
2단계: 삽입된 문서 확인
find() 메서드를 사용하면 컬렉션의 모든 문서를 조회할 수 있습니다. 가독성을 높이기 위해 pretty()도 함께 사용합니다.
> db.insertOneRecordDemo.find().pretty();
실행 결과는 다음과 같습니다.
{
"_id" : ObjectId("5c9534de16f542d757e2b452"),
"UserName" : "Larry",
"UserAge" : 23
}
{
"_id" : ObjectId("5c9534e816f542d757e2b453"),
"UserName" : "Chris",
"UserAge" : 26
}
{
"_id" : ObjectId("5c9534f116f542d757e2b454"),
"UserName" : "David",
"UserAge" : 25
}3단계: 한 데이터베이스에서 다른 데이터베이스로 레코드 삽입
이제 소스 컬렉션의 모든 문서를 변수에 담은 뒤, use 명령어로 대상 데이터베이스로 전환하고 forEach()문자>를 통해 각 문서를 새 데이터베이스의 컬렉션에 삽입합니다.
> var AllDocumentsFromSourceCollection = db.insertOneRecordDemo.find();
> use sample;
switched to db sample
> AllDocumentsFromSourceCollection.forEach(function(allRecords){ db.getAllRecordsFromSourceCollectionDemo.insert(allRecords) });여기서 핵심은 다음과 같습니다.
- find() 결과를 변수에 저장하여 커서(cursor) 형태로 유지합니다.
- use sample; 명령으로 작업 대상 데이터베이스를 "test"에서 "sample"로 전환합니다.
- forEach()문자> 반복문으로 각 레코드를 대상 컬렉션에 하나씩 삽입합니다.
4단계: 삽입 결과 검증
레코드가 실제로 삽입되었는지 확인해 보겠습니다. 아래 쿼리를 실행합니다.
> db.getAllRecordsFromSourceCollectionDemo.find().pretty();
실행 결과는 다음과 같습니다.
{
"_id" : ObjectId("5c9534de16f542d757e2b452"),
"UserName" : "Larry",
"UserAge" : 23
}
{
"_id" : ObjectId("5c9534e816f542d757e2b453"),
"UserName" : "Chris",
"UserAge" : 26
}
{
"_id" : ObjectId("5c9534f116f542d757e2b454"),
"UserName" : "David",
"UserAge" : 25
}소스 데이터베이스의 모든 문서가 ObjectId까지 그대로 유지된 상태로 "sample" 데이터베이스에 성공적으로 복사된 것을 확인할 수 있습니다.
5단계: 컬렉션 목록 확인
마지막으로 show collections 명령어를 사용해 "sample" 데이터베이스에 해당 컬렉션이 실제로 존재하는지 확인할 수 있습니다.
> show collections;
실행 결과는 다음과 같습니다.
arraySizeErrorDemo basicInformationDemo copyThisCollectionToSampleDatabaseDemo deleteAllRecordsDemo deleteDocuments deleteDocumentsDemo deleteSomeInformation documentWithAParticularFieldValueDemo employee findListOfIdsDemo findSubstring getAllRecordsFromSourceCollectionDemo getElementWithMaxIdDemo internalArraySizeDemo largestDocumentDemo makingStudentInformationClone oppositeAddToSetDemo prettyDemo returnOnlyUniqueValuesDemo selectWhereInDemo sourceCollection studentInformation sumOfValueDemo truncateDemo updateInformation userInformation
출력 목록에서 getAllRecordsFromSourceCollectionDemo 컬렉션이 포함되어 있는 것을 볼 수 있습니다. 이것으로 한 MongoDB 데이터베이스의 레코드를 다른 데이터베이스에 삽입하는 전체 과정이 완료되었습니다.