MongoDB에서 배열(array) 안에 포함된 특정 요소를 일치시켜 조회하려면 $or 연산자와 limit(1) 메서드를 함께 사용할 수 있습니다. 이번 글에서는 실제 예제를 통해 배열 내 요소를 매칭하는 과정을 단계별로 살펴보겠습니다.
1. 테스트용 컬렉션 생성 및 문서 삽입
먼저 insertOne() 메서드를 사용해 컬렉션을 생성하고 학생 정보가 담긴 문서 두 개를 삽입합니다. 각 문서에는 국가명과 기술 스택을 담은 하위 문서 배열이 포함되어 있습니다.
> db.matchElementInArrayDemo.insertOne(
... {
... "StudentName" : "Chris" ,
... "StudentOtherDetails" :
... [
... {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"},
... {"StudentCountryName" : "UK" , "StudentSkills" : "Java"}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd423282cba06f46efe9ee2")
}
> db.matchElementInArrayDemo.insertOne(
... {
... "StudentName" : "Chris" ,
... "StudentOtherDetails" :
... [
... {"StudentCountryName" : "AUS" , "StudentSkills" : "PHP"},
... {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd423412cba06f46efe9ee3")
}2. 저장된 전체 문서 확인하기
find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 확인할 수 있습니다.
> db.matchElementInArrayDemo.find().pretty();
위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
{
"_id" : ObjectId("5cd423282cba06f46efe9ee2"),
"StudentName" : "Chris",
"StudentOtherDetails" : [
{
"StudentCountryName" : "US",
"StudentSkills" : "MongoDB"
},
{
"StudentCountryName" : "UK",
"StudentSkills" : "Java"
}
]
}
{
"_id" : ObjectId("5cd423412cba06f46efe9ee3"),
"StudentName" : "Chris",
"StudentOtherDetails" : [
{
"StudentCountryName" : "AUS",
"StudentSkills" : "PHP"
},
{
"StudentCountryName" : "US",
"StudentSkills" : "MongoDB"
}
]
}3. $or 연산자로 배열 내 요소 일치시키기
이제 핵심 부분입니다. $or 연산자를 사용하면 여러 조건 중 하나라도 충족하는 문서를 조회할 수 있습니다. 아래 쿼리는 StudentCountryName이 US이거나 StudentSkills가 MongoDB인 요소를 배열 안에 포함한 문서를 찾고, limit(1)을 적용해 첫 번째 결과 한 건만 반환합니다.
> db.matchElementInArrayDemo.find( { $or : [ {"StudentOtherDetails.StudentCountryName": "US" } ,{"StudentOtherDetails.StudentSkills": "MongoDB" } ] } ).limit(1);실행 결과는 다음과 같습니다.
{ "_id" : ObjectId("5cd423282cba06f46efe9ee2"), "StudentName" : "Chris", "StudentOtherDetails" : [ { "StudentCountryName" : "US", "StudentSkills" : "MongoDB" }, { "StudentCountryName" : "UK", "StudentSkills" : "Java" } ] }정리
MongoDB에서 배열 내부의 필드 값을 기준으로 문서를 검색할 때는 점 표기법(dot notation)으로 배열 내 하위 필드에 접근하고, 복수 조건이 필요하면 $or 연산자를 활용하면 됩니다. 여기에 limit()을 조합하면 원하는 개수만큼의 결과만 효율적으로 가져올 수 있습니다.