0Pricing
MongoDB Academy · 강의

데이터베이스 프로파일러와 느린 쿼리 로그

학습자는 프로파일러를 활성화하고 slowms 임계값을 설정한 뒤 system.profile을 쿼리해 비용이 가장 큰 작업을 찾습니다.

데이터베이스 프로파일러와 느린 쿼리 로그은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Profiling Matters

MongoDB can run thousands of queries per second, but a handful of slow queries can drag down an entire application. The database profiler and the slow query log are your primary tools for finding these expensive operations. They record query execution details — duration, documents examined, index usage — so you can identify and fix bottlenecks before users feel them.

Profiler Levels: 0, 1, and 2

The profiler has three levels: Level 0 — off, nothing is recorded. Level 1 — records operations that take longer than the slowms threshold (default 100 ms). This is the recommended production setting. Level 2 — records every operation regardless of duration. Level 2 is useful during debugging but creates too much write overhead for sustained production use.

// Enable level 1 profiling with 50ms threshold
db.setProfilingLevel(1, { slowms: 50 })

// Enable level 2 (capture everything)
db.setProfilingLevel(2)

// Turn profiling off
db.setProfilingLevel(0)

The system.profile Collection

Profiled operations are written to the system.profile capped collection in each database. Each document in this collection represents one operation and contains: op (operation type), ns (namespace), command (the query or update), millis (duration), keysExamined, docsExamined, nreturned, and the execStats tree.

// Find the 5 slowest operations in the last hour
db.system.profile.find({
  ts: { $gt: new Date(Date.now() - 3600000) }
}).sort({ millis: -1 }).limit(5).pretty()

Key Fields in a Profile Document

The most diagnostic fields in a profile entry are: millis — total elapsed time. docsExamined — how many documents MongoDB read to satisfy the query. keysExamined — index entries scanned. nreturned — how many documents were returned. A healthy query has docsExamined / nreturned close to 1; a ratio of 1000:1 suggests a missing or inefficient index.

// Inspect ratio of docsExamined to nreturned
db.system.profile.find({},{
  millis: 1, docsExamined: 1, nreturned: 1, command: 1
}).sort({ millis: -1 }).limit(10)
// If docsExamined >> nreturned, you need a better index

The slowms Threshold

slowms is the cutoff in milliseconds for level 1 profiling. Only operations taking longer than this value are recorded. The default is 100 ms; you can lower it to 20–50 ms to catch more operations during an investigation, then raise it back to 100 ms (or higher) in production to reduce overhead. The setting is per-database and is not persisted across restarts unless set in mongod.conf.

// Set via mongod.conf (persists across restarts)
// operationProfiling:
//   mode: slowOp
//   slowOpThresholdMs: 100

// Or dynamically at runtime (applies until restart)
db.adminCommand({ profile: 1, slowms: 20 })

Reading the Slow Query Log

Even with the profiler off, MongoDB writes slow operations to its log file. Each slow query log entry includes the operation type, namespace, duration, query shape, and plan summary. Log lines with COLLSCAN in the planSummary field are guaranteed to be missing an index. Log messages begin with Slow query and appear at log verbosity level 0.

// In the mongod log (or Atlas Log viewer), look for lines like:
// 2025-01-15T10:23:45 COMMAND mydb.orders command: find { filter: { status: 'pending' } }
//   planSummary: COLLSCAN
//   keysExamined: 0 docsExamined: 150000 nreturned: 23
//   protocol: op_msg 1250ms

Atlas Performance Advisor

MongoDB Atlas includes the Performance Advisor, which automatically analyzes your slow query logs and recommends indexes. It groups similar queries by their query shape (filter structure without values), shows the average execution time, and generates the exact createIndex command you need. It is the fastest way to identify missing indexes in production without manually parsing logs.

Querying system.profile Effectively

You can filter system.profile by operation type, namespace, or any field. Common analysis patterns: find all collection scans, find all slow aggregations, and find all operations on a specific collection. Sort by millis descending to see the worst offenders first.

// Find all collection scans recorded by the profiler
db.system.profile.find({
  'execStats.stage': 'COLLSCAN'
}).sort({ millis: -1 })

// Find slow ops on a specific collection
db.system.profile.find({
  ns: 'mydb.orders',
  millis: { $gt: 200 }
}).sort({ millis: -1 })

Profiler Performance Overhead

Each profile entry is a write to the capped system.profile collection, which adds a small but measurable overhead. Level 1 (slow op only) is safe for most production workloads. Level 2 (all ops) can increase latency by 5–20% on busy clusters and should only be run for short debugging sessions. Always return to level 0 or 1 after a profiling session.

// Check current profiling level and threshold
db.getProfilingStatus()
// { was: 1, slowms: 100, sampleRate: 1 }

currentOp: Catching Runaway Queries Live

db.currentOp() shows all operations currently executing on the server — not just slow ones that already finished. Use it to catch long-running queries in real time, identify locks, and kill runaway operations with db.killOp(opid). Combine it with the profiler for a complete picture of past and present slow operations.

// Find all ops running longer than 5 seconds
db.currentOp({
  active: true,
  secs_running: { $gt: 5 }
})

// Kill a specific runaway op by opid
db.killOp(12345)

Profiling Workflow: Investigate and Fix

A practical profiling workflow: 1) Set profiling level 1 with a 50 ms threshold. 2) Let the system run for 15–30 minutes under real traffic. 3) Query system.profile sorted by millis descending. 4) For each slow query, run explain('executionStats') on the same query. 5) Create the missing index. 6) Return profiler to normal threshold. Repeat until all critical queries hit indexes.

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: profiling level 1 records slow operations above the slowms threshold into system.profile, high docsExamined/nreturned ratios and COLLSCAN in planSummary identify missing indexes, and db.currentOp() lets you catch and kill long-running queries in real time. Next up we explore the ESR principle for designing optimal compound indexes.

자주 묻는 질문

“데이터베이스 프로파일러와 느린 쿼리 로그” 강의는 무료인가요?

네 — “데이터베이스 프로파일러와 느린 쿼리 로그” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“데이터베이스 프로파일러와 느린 쿼리 로그”에서 뭘 배우나요?

학습자는 프로파일러를 활성화하고 slowms 임계값을 설정한 뒤 system.profile을 쿼리해 비용이 가장 큰 작업을 찾습니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“데이터베이스 프로파일러와 느린 쿼리 로그” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 데이터베이스 프로파일러와 느린 쿼리 로그
  2. 복합 인덱스 접두사 규칙과 ESR 원칙
  3. 인덱스 교차와 복합 인덱스 비교
  4. 집계 파이프라인 최적화 팁
← MongoDB Academy(으)로 돌아가기