MongoDB에서 문서 내부에 중첩된 배열(임베디드 배열)에서 원하는 요소만 골라내고 싶다면, 애그리게이션 파이프라인의 $unwind와 $match를 점 표기법(dot notation)과 함께 사용하면 됩니다.
1. 샘플 컬렉션 생성
먼저 실습에 사용할 컬렉션을 만들고 문서를 삽입해 보겠습니다.
> db.demo641.insert(
... {
... ProductId:101,
... "ProductInformation":
... [
... {
... ProductName:"Product-1",
... "ProductPrice":1000
... },
... {
... ProductName:"Product-2",
... "ProductPrice":500
... },
... {
... ProductName:"Product-3",
... "ProductPrice":2000
... },
... {
... ProductName:"Product-4",
... "ProductPrice":3000
... }
... ]
... }
... );
WriteResult({ "nInserted" : 1 })2. 전체 문서 확인하기
find() 메서드를 사용하면 컬렉션의 모든 문서를 조회할 수 있습니다.
> db.demo641.find();
위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
{
"_id" : ObjectId("5e9c31d46c954c74be91e6e2"), "ProductId" : 101, "ProductInformation" :
[
{ "ProductName" : "Product-1", "ProductPrice" : 1000 },
{ "ProductName" : "Product-2", "ProductPrice" : 500 },
{ "ProductName" : "Product-3", "ProductPrice" : 2000 },
{ "ProductName" : "Product-4", "ProductPrice" : 3000 }
]
}3. $unwind와 $match로 특정 요소만 필터링하기
임베디드 배열에서 조건에 맞는 요소만 가져오려면 아래와 같은 애그리게이션 쿼리를 사용합니다.
> db.demo641.aggregate([
... {$unwind: "$ProductInformation"},
... {$match: { "ProductInformation.ProductPrice": {$in :[1000, 2000]}} },
... {$project: {_id: 0, ProductInformation: 1} }
... ]).pretty();각 단계의 역할은 다음과 같습니다.
- $unwind: ProductInformation 배열을 개별 문서로 분해합니다.
- $match: 점 표기법으로 배열 내부의 ProductPrice 필드에 접근하여 가격이 1000 또는 2000인 요소만 걸러냅니다.
- $project: _id 필드를 제외하고 ProductInformation만 출력되도록 지정합니다.
쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
{
"ProductInformation" : {
"ProductName" : "Product-1",
"ProductPrice" : 1000
}
}
{
"ProductInformation" : {
"ProductName" : "Product-3",
"ProductPrice" : 2000
}
}이처럼 $unwind로 배열을 분해한 뒤 $match로 조건을 적용하면, MongoDB의 임베디드 배열에서도 원하는 특정 요소를 손쉽게 추출할 수 있습니다.