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

MongoDB 컬렉션에서 모든 중첩 필드를 검색하는 방법

개요

MongoDB에서 배열 형태로 저장된 중첩 필드(내장 문서)를 모두 조회하려면 aggregate() 메서드를 사용하면 됩니다. 이 글에서는 애그리게이션 파이프라인의 $unwind$project 단계를 활용해 중첩된 필드를 평탄화(flatten)하여 추출하는 방법을 단계별로 살펴봅니다.

1. 샘플 컬렉션 생성하기

먼저 insertOne() 메서드를 사용해 데모용 컬렉션 demo138에 문서를 삽입합니다.

> db.demo138.insertOne({"Id":101,"PlayerDetails":[{"PlayerName":"Chris","PlayerScore":400},{"PlayerName":"David","PlayerScore":1000}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31bb9ffdf09dd6d08539a1")
}
> db.demo138.insertOne({"Id":102,"PlayerDetails":[{"PlayerName":"Bob","PlayerScore":500},{"PlayerName":"Carol","PlayerScore":600}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31bbcefdf09dd6d08539a2")
}

2. 저장된 문서 확인하기

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

> db.demo138.find();

위 명령을 실행하면 다음과 같은 결과가 출력됩니다.

{
   "_id" : ObjectId("5e31bb9ffdf09dd6d08539a1"), "Id" : 101, "PlayerDetails" : [
      { "PlayerName" : "Chris", "PlayerScore" : 400 },
      { "PlayerName" : "David", "PlayerScore" : 1000 }
   ]
}
{
   "_id" : ObjectId("5e31bbcefdf09dd6d08539a2"), "Id" : 102, "PlayerDetails" : [
      { "PlayerName" : "Bob", "PlayerScore" : 500 }, { "PlayerName" : "Carol", "PlayerScore" : 600 }
   ]
}

3. 중첩 필드를 검색하는 쿼리 작성하기

컬렉션에서 모든 중첩 필드를 가져오려면 아래와 같이 aggregate() 쿼리를 작성합니다. 먼저 $unwind가 PlayerDetails 배열을 개별 문서로 분해하고, 이어서 $project가 각 요소 안의 PlayerName과 PlayerScore 필드만 추출합니다.

> db.demo138.aggregate([{ $unwind:"$PlayerDetails" }, { $project: { "PlayerName":"$PlayerDetails.PlayerName", "PlayerScore":"$PlayerDetails.PlayerScore" } } ] );

쿼리 실행 결과는 다음과 같습니다.

{ "_id" : ObjectId("5e31bb9ffdf09dd6d08539a1"), "PlayerName" : "Chris", "PlayerScore" : 400 }
{ "_id" : ObjectId("5e31bb9ffdf09dd6d08539a1"), "PlayerName" : "David", "PlayerScore" : 1000 }
{ "_id" : ObjectId("5e31bbcefdf09dd6d08539a2"), "PlayerName" : "Bob", "PlayerScore" : 500 }
{ "_id" : ObjectId("5e31bbcefdf09dd6d08539a2"), "PlayerName" : "Carol", "PlayerScore" : 600 }

정리

이처럼 aggregate() 파이프라인에서 $unwind로 배열을 분해한 뒤 $project로 원하는 하위 필드를 지정하면, 중첩된 구조를 손쉽게 평탄화하여 조회할 수 있습니다. 배열 요소마다 하나의 결과 문서가 생성되므로, 플레이어별 점수처럼 개별 항목 단위의 데이터 분석에 유용하게 활용할 수 있습니다.