개요
배열 형태로 저장된 데이터 중에서 특정 필드만 추출하고 싶을 때는 집계 파이프라인(aggregate)의 $project 연산자를 활용하면 됩니다. 이 글에서는 예제 컬렉션을 직접 만들어 보고, $project와 $arrayElemAt 연산자를 조합해 배열 안의 특정 필드 값을 반환하는 방법을 단계별로 살펴보겠습니다.
1. 샘플 컬렉션 생성하기
먼저 insertOne() 메서드로 문서를 삽입하여 컬렉션을 생성합니다. 이 문서는 StudentId와 함께 학생 정보(StudentDetails) 배열을 포함하고 있습니다.
> db.returnSpecificFieldDemo.insertOne(
{
"StudentId":1,
"StudentDetails": [
{
"StudentName":"Larry",
"StudentAge":21,
"StudentCountryName":"US"
},
{
"StudentName":"Chris",
"StudentAge":23,
"StudentCountryName":"AUS"
}
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5ce23d3236e8b255a5eee943")
}
2. 전체 문서 확인하기
find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 조회할 수 있습니다.
> db.returnSpecificFieldDemo.find().pretty();
위 쿼리를 실행하면 다음과 같은 출력 결과를 얻을 수 있습니다.
{
"_id" : ObjectId("5ce23d3236e8b255a5eee943"),
"StudentId" : 1,
"StudentDetails" : [
{
"StudentName" : "Larry",
"StudentAge" : 21,
"StudentCountryName" : "US"
},
{
"StudentName" : "Chris",
"StudentAge" : 23,
"StudentCountryName" : "AUS"
}
]
}3. 배열에서 특정 필드 반환하기
배열 내부의 특정 필드 값만 가져오려면 aggregate()의 $project 단계에서 $arrayElemAt 연산자를 사용합니다. $arrayElemAt은 지정한 인덱스 위치에 있는 배열 요소를 반환하는 연산자로, 아래 예제에서는 인덱스 1(두 번째 요소)에 해당하는 StudentCountryName 값을 추출합니다.
> db.returnSpecificFieldDemo.aggregate([{$project:{_id:0, StudentId:'$StudentId', StudentCountryName:{ $arrayElemAt: ['$StudentDetails.StudentCountryName',1] }}}]);쿼리 실행 결과는 다음과 같습니다.
{ "StudentId" : 1, "StudentCountryName" : "AUS" }마무리
이처럼 MongoDB에서는 $project와 $arrayElemAt을 조합하면 배열에 포함된 여러 필드 중 원하는 필드만 깔끔하게 추출할 수 있습니다. _id:0 옵션으로 불필요한 _id 필드를 제외했고, 인덱스 번호를 변경하면 배열의 다른 위치에 있는 요소도 손쉽게 조회할 수 있습니다.