MongoDB에서 여러 필드의 OR 조건을 위한 인덱스 생성 방법
여러 필드를 대상으로 하는 쿼리를 효율적으로 처리하려면 복합 인덱스(compound index)를 활용해야 합니다. MongoDB에서는 ensureIndex() 메서드를 사용해 인덱스를 생성할 수 있으며, 이 메서드에 여러 개의 필드를 함께 전달하면 하나의 인덱스가 여러 필드를 커버하도록 만들 수 있습니다.
참고로 ensureIndex()는 최신 버전의 MongoDB에서 더 이상 사용되지 않으므로(deprecated), 실제 운영 환경에서는 동일한 기능을 수행하는 createIndex()를 사용하는 것이 좋습니다.
1. 복합 인덱스 생성하기
아래 예제에서는 demo53 컬렉션에 두 개의 복합 인덱스를 생성합니다. 첫 번째 인덱스는 StudentFirstName과 StudentAge 필드의 조합이며, 두 번째 인덱스는 StudentFirstName과 StudentCountryName 필드의 조합입니다.
> db.demo53.ensureIndex({"StudentFirstName":1,"StudentAge":1});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.demo53.ensureIndex({"StudentFirstName":1,"StudentCountryName":1});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}인덱스 값으로 1은 오름차순(ascending) 정렬을 의미하며, -1을 지정하면 내림차순(descending) 정렬로 인덱스가 생성됩니다.
2. 문서 삽입하기
인덱스가 준비되었으면 insertOne() 메서드를 사용해 컬렉션에 문서를 추가합니다.
>db.demo53.insertOne({"StudentFirstName":"Chris","StudentAge":21,"StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e271431cfb11e5c34d89911")
}
>db.demo53.insertOne({"StudentFirstName":"David","StudentAge":23,"StudentCountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e27143ccfb11e5c34d89912")
}
>db.demo53.insertOne({"StudentFirstName":"Mike","StudentAge":24,"StudentCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e27144bcfb11e5c34d89913")
}3. 저장된 문서 확인하기
find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 조회할 수 있습니다.
> db.demo53.find();
위 명령을 실행하면 다음과 같은 결과가 출력됩니다.
{ "_id" : ObjectId("5e271431cfb11e5c34d89911"), "StudentFirstName" : "Chris", "StudentAge" : 21, "StudentCountryName" : "US" }
{ "_id" : ObjectId("5e27143ccfb11e5c34d89912"), "StudentFirstName" : "David", "StudentAge" : 23, "StudentCountryName" : "UK" }
{ "_id" : ObjectId("5e27144bcfb11e5c34d89913"), "StudentFirstName" : "Mike", "StudentAge" : 24, "StudentCountryName" : "AUS" }정리
이처럼 복합 인덱스를 미리 생성해 두면, 여러 필드를 조건으로 사용하는 $or 또는 일반 조회 쿼리에서 MongoDB가 전체 컬렉션 스캔(collection scan) 대신 인덱스를 활용할 수 있어 쿼리 성능이 크게 향상됩니다. 특히 자주 검색되는 필드 조합을 파악한 후 해당 조합으로 인덱스를 설계하는 것이 데이터베이스 최적화의 핵심입니다.