MongoDB에서 explain()로 컬렉션 실행 통계 확인하기
MongoDB에서 쿼리가 어떻게 실행되는지, 그리고 얼마나 효율적으로 동작하는지 분석하고 싶다면 explain() 메서드를 활용하면 됩니다. 특히 인자로 "executionStats"를 전달하면 실제 실행에 소요된 시간, 검사한 문서 수 등 상세한 통계까지 확인할 수 있어 쿼리 최적화에 매우 유용합니다.
이번 글에서는 예제 컬렉션을 생성하고, explain()을 사용해 실행 통계를 조회하는 과정을 단계별로 살펴보겠습니다.
1. 컬렉션 생성 및 문서 삽입
먼저 insertOne() 메서드를 사용해 demo157 컬렉션에 문서 두 개를 삽입합니다.
> db.demo157.insertOne({"Status":"Active"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e354fdffdf09dd6d08539fc")
}
> db.demo157.insertOne({"Status":"InActive"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e354fe3fdf09dd6d08539fd")
}2. find()로 저장된 문서 확인
find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 조회할 수 있습니다.
> db.demo157.find();
위 명령을 실행하면 다음과 같은 결과가 출력됩니다.
{ "_id" : ObjectId("5e354fdffdf09dd6d08539fc"), "Status" : "Active" }
{ "_id" : ObjectId("5e354fe3fdf09dd6d08539fd"), "Status" : "InActive" }3. explain("executionStats")로 실행 통계 조회
이제 $in 연산자를 사용한 쿼리에 explain("executionStats")를 적용해 보겠습니다.
> db.demo157.find({Status: { $in: ['Active','InActive'] }}).explain("executionStats");실행하면 아래와 같이 쿼리 계획(queryPlanner)과 실제 실행 통계(executionStats)가 포함된 상세한 결과가 반환됩니다.
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "test.demo157",
"indexFilterSet" : false,
"parsedQuery" : {
"Status" : {
"$in" : [
"Active",
"InActive"
]
}
},
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"Status" : {
"$in" : [
"Active",
"InActive"
]
}
},
"direction" : "forward"
},
"rejectedPlans" : [ ]
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 2,
"executionTimeMillis" : 18,
"totalKeysExamined" : 0,
"totalDocsExamined" : 2,
"executionStages" : {
"stage" : "COLLSCAN",
"filter" : {
"Status" : {
"$in" : [
"Active",
"InActive"
]
}
},
"nReturned" : 2,
"executionTimeMillisEstimate" : 0,
"works" : 4,
"advanced" : 2,
"needTime" : 1,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1,
"invalidates" : 0,
"direction" : "forward",
"docsExamined" : 2
}
},
"serverInfo" : {
"host" : "DESKTOP-QN2RB3H",
"port" : 27017,
"version" : "4.0.5",
"gitVersion" : "3739429dd92b92d1b0ab120911a23d50bf03c412"
},
"ok" : 1
}주요 결과 항목 해석
- nReturned : 쿼리 조건에 일치하여 반환된 문서 수 (여기서는 2개)
- totalDocsExamined : 쿼리 실행 중 검사한 전체 문서 수
- totalKeysExamined : 인덱스 키를 검사한 수 (인덱스를 사용하지 않았으므로 0)
- executionTimeMillis : 쿼리 실행에 소요된 시간(밀리초)
- stage : COLLSCAN : 인덱스 없이 컬렉션 전체를 스캔(full collection scan)했음을 의미
이처럼 explain("executionStats")를 활용하면 쿼리가 인덱스를 사용하는지, 얼마나 많은 문서를 검사하는지, 실행 시간은 어느 정도인지 파악할 수 있습니다. 분석 결과를 바탕으로 적절한 인덱스를 추가하거나 쿼리 구조를 개선하면 데이터베이스 성능을 크게 향상시킬 수 있습니다.