Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

MongoDB 집계 프레임워크로 내장된 객체를 문서로 조회하는 방법

MongoDB에서 문서 안에 포함된(내장된) 객체를 마치 독립적인 문서처럼 조회하고 싶다면, 집계 프레임워크의 $replaceRoot 단계를 활용하면 됩니다. $replaceRoot는 지정한 필드를 새로운 루트(newRoot)로 승격시켜 주기 때문에, 중첩되어 있던 객체를 최상위 문서 형태로 손쉽게 변환할 수 있습니다.

1. 샘플 컬렉션 생성하기

먼저 예제에 사용할 컬렉션을 만들고 문서를 삽입해 보겠습니다. 각 문서에는 사용자 정보를 담은 UserDetails라는 내장 객체가 들어 있습니다.

> db.embeddedObjectDemo.insertOne(
   { _id: new ObjectId(),
      "UserDetails": { "UserName": "John", "UserAge": 24, "UserEmailId": "John22@gmail.com" }
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ced580fef71edecf6a1f693")
}
> db.embeddedObjectDemo.insertOne( { _id: new ObjectId(), "UserDetails": { "UserName": "Carol", "UserAge": 26, "UserEmailId": "Carol123@gmail.com" } } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ced5828ef71edecf6a1f694")
}

2. find() 메서드로 전체 문서 확인하기

find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 확인할 수 있습니다.

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

실행 결과는 다음과 같습니다. UserDetails 필드가 중첩된 객체 형태로 함께 출력되는 것을 확인할 수 있습니다.

{
   "_id" : ObjectId("5ced580fef71edecf6a1f693"),
   "UserDetails" : {
      "UserName" : "John",
      "UserAge" : 24,
      "UserEmailId" : "John22@gmail.com"
   }
}
{
   "_id" : ObjectId("5ced5828ef71edecf6a1f694"),
   "UserDetails" : {
      "UserName" : "Carol",
      "UserAge" : 26,
      "UserEmailId" : "Carol123@gmail.com"
   }
}

3. $replaceRoot로 내장 객체를 문서로 조회하기

이제 집계 프레임워크에서 $replaceRoot를 사용해 UserDetails 객체를 최상위 문서로 조회해 보겠습니다.

> db.embeddedObjectDemo.aggregate( [
   {
      $replaceRoot: { newRoot: "$UserDetails" }
   }
] );

실행 결과 UserDetails 래퍼 없이 각 사용자 정보가 개별 문서로 반환됩니다.

{ "UserName" : "John", "UserAge" : 24, "UserEmailId" : "John22@gmail.com" }
{ "UserName" : "Carol", "UserAge" : 26, "UserEmailId" : "Carol123@gmail.com" }

참고: $replaceRoot는 지정한 필드가 존재하지 않거나 문서 타입이 아닌 경우 오류가 발생할 수 있습니다. 따라서 일부 문서에 해당 필드가 없을 가능성이 있다면, 집계 파이프라인 앞쪽에 $match로 대상 문서를 먼저 걸러내거나 $project와 함께 사용하는 것이 안전합니다.