MongoDB에서 정수 배열로 문서를 검색하는 방법
MongoDB에서 정수 배열 필드를 기준으로 문서를 검색하려면 $where 연산자를 사용할 수 있습니다. $where 연산자는 JavaScript 표현식을 지원하기 때문에 배열의 길이 확인처럼 일반적인 쿼리 연산자로는 처리하기 어려운 조건도 손쉽게 구현할 수 있습니다.
아래에서는 실제 예제를 통해 컬렉션 생성부터 다양한 검색 조건 적용까지 단계별로 살펴보겠습니다.
1단계: 문서가 포함된 컬렉션 생성
먼저 학생 이름(StudentFirstName)과 점수 배열(StudentScores)을 담은 컬렉션을 만들어 보겠습니다.
> db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"John","StudentScores":[45,78,89,90]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a219345990cee87fd88c")
}
> db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Larry","StudentScores":[45,43,34,33]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a22a345990cee87fd88d")
}
> db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Chris","StudentScores":[]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a23c345990cee87fd88e")
}
> db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"David","StudentScores":[99]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a24d345990cee87fd88f")
}
2단계: 전체 문서 조회하기
find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 확인할 수 있습니다.
> db.searchDocumentArrayIntegerDemo.find().pretty();
위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
{
"_id" : ObjectId("5cd2a219345990cee87fd88c"),
"StudentFirstName" : "John",
"StudentScores" : [
45,
78,
89,
90
]
}
{
"_id" : ObjectId("5cd2a22a345990cee87fd88d"),
"StudentFirstName" : "Larry",
"StudentScores" : [
45,
43,
34,
33
]
}
{
"_id" : ObjectId("5cd2a23c345990cee87fd88e"),
"StudentFirstName" : "Chris",
"StudentScores" : [ ]
}
{
"_id" : ObjectId("5cd2a24d345990cee87fd88f"),
"StudentFirstName" : "David",
"StudentScores" : [
99
]
}
케이스 1: 배열에 최소 하나 이상의 값이 있는 경우
배열 길이가 1 이상인 문서만 검색하려면 $where 연산자에 JavaScript 표현식을 전달하면 됩니다.
> db.searchDocumentArrayIntegerDemo.find({ $where: "this.StudentScores.length >= 1" } );
실행 결과는 다음과 같습니다. 빈 배열을 가진 Chris의 문서는 조건에 해당하지 않아 결과에서 제외됩니다.
{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentFirstName" : "John", "StudentScores" : [ 45, 78, 89, 90 ] }
{ "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentFirstName" : "Larry", "StudentScores" : [ 45, 43, 34, 33 ] }
{ "_id" : ObjectId("5cd2a24d345990cee87fd88f"), "StudentFirstName" : "David", "StudentScores" : [ 99 ] }
케이스 2: 특정 공통 값을 포함하는 경우
여러 문서의 배열에 공통으로 포함된 특정 값(예: 45)을 기준으로 검색하려면 필드 이름에 직접 값을 지정하면 됩니다. 두 번째 인자인 {StudentScores:1}은 프로젝션(projection)으로, 결과에서 _id와 StudentScores 필드만 반환하도록 제한하는 역할을 합니다.
> db.searchDocumentArrayIntegerDemo.find({StudentScores: 45}, {StudentScores:1});
실행 결과, 점수 배열에 45가 포함된 John과 Larry의 문서만 조회됩니다.
{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentScores" : [ 45, 78, 89, 90 ] }
{ "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentScores" : [ 45, 43, 34, 33 ] }
마무리 및 참고 사항
이처럼 MongoDB에서는 $where 연산자를 활용해 배열의 길이 조건 검색이 가능하고, 단순 값 매칭은 필드명에 직접 조건을 지정하여 해결할 수 있습니다.
다만 $where 연산자는 각 문서마다 JavaScript를 실행하기 때문에 성능 부담이 클 수 있습니다. 대량의 데이터를 다루는 운영 환경에서는 가능한 한 일반 쿼리 연산자를 사용하는 것이 좋습니다. 예를 들어 배열의 크기가 정확히 n인 문서를 찾을 때는 { field: { $size: n } }, 배열 안의 요소 조건을 검사할 때는 $elemMatch 연산자를 활용하면 더 효율적입니다.