MongoDB에서 배열 필드의 여러 요소를 동시에 만족하는 문서를 조회해야 할 때가 있습니다. 이럴 때 유용하게 사용할 수 있는 것이 바로 $elemMatch 연산자입니다.
$elemMatch 연산자란?
$elemMatch는 배열 필드 안에 있는 단일 요소가 지정된 모든 쿼리 조건을 동시에 충족하는 경우에만 해당 문서를 매칭하는 연산자입니다. 일반적인 조건 나열 방식과 달리, 하나의 배열 요소 내에서 여러 필드가 모두 일치해야 한다는 점이 핵심입니다.
1. 테스트용 컬렉션 생성
먼저 예제로 사용할 컬렉션을 만들고 문서를 삽입해 보겠습니다.
> db.filterBySeveralElementsDemo.insertOne(
{
"_id": 100,
"StudentDetails": [
{
"StudentName": "John",
"StudentCountryName": "US"
},
{
"StudentName": "Carol",
"StudentCountryName": "UK"
}
]
}
);
{ "acknowledged" : true, "insertedId" : 100 }
> db.filterBySeveralElementsDemo.insertOne(
{
"_id": 101,
"StudentDetails": [
{
"StudentName": "Sam",
"StudentCountryName": "AUS"
},
{
"StudentName": "Chris",
"StudentCountryName": "US"
}
]
}
);
{ "acknowledged" : true, "insertedId" : 101 }2. 전체 문서 확인하기
find() 메서드를 사용해 컬렉션에 저장된 모든 문서를 조회합니다.
> db.filterBySeveralElementsDemo.find().pretty();
위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
{
"_id" : 100,
"StudentDetails" : [
{
"StudentName" : "John",
"StudentCountryName" : "US"
},
{
"StudentName" : "Carol",
"StudentCountryName" : "UK"
}
]
}
{
"_id" : 101,
"StudentDetails" : [
{
"StudentName" : "Sam",
"StudentCountryName" : "AUS"
},
{
"StudentName" : "Chris",
"StudentCountryName" : "US"
}
]
}3. 여러 배열 요소 조건으로 필터링하기
이제 $elemMatch를 사용해 학생 이름이 Sam이면서 국가가 AUS인 요소를 포함한 문서만 조회해 보겠습니다.
> db.filterBySeveralElementsDemo.find({
StudentDetails: {
$elemMatch: { StudentName: 'Sam', StudentCountryName: 'AUS' }
}
}).pretty();실행 결과는 다음과 같습니다.
{
"_id" : 101,
"StudentDetails" : [
{
"StudentName" : "Sam",
"StudentCountryName" : "AUS"
},
{
"StudentName" : "Chris",
"StudentCountryName" : "US"
}
]
}정리
$elemMatch를 사용하면 배열 내 같은 요소가 여러 조건을 모두 만족하는 문서만 정확하게 필터링할 수 있습니다. 만약 조건을 단순히 나열하면 각 조건이 서로 다른 배열 요소에서 매칭될 수 있으므로, 하나의 요소에 대해 복수 조건을 검사할 때는 반드시 $elemMatch를 사용하는 것이 좋습니다.