Skip to content

MongoDB 치트시트

대용량 데이터 저장을 위한 NoSQL 문서 데이터베이스입니다.

01

시작하기

MongoDB 연결

mongosh는 현대적인 MongoDB 셸입니다(레거시 mongo 셸 대체). 연결 문자열은 mongodb://[user:pass@]host[:port]/[db][?options] URI 형식을 따릅니다. /admin 데이터베이스가 기본 인증 데이터베이스입니다. URI에 데이터베이스를 덧붙여 특정 데이터베이스에 바로 연결할 수 있습니다.

mongodb
# connect to a local server on default port
mongosh

# connect to a specific host and port
mongosh "mongodb://localhost:27017"

# connect with authentication
mongosh "mongodb://user:pass@localhost:27017/admin"

# connect to a specific database directly
mongosh "mongodb://localhost:27017/mydb"

# show connection info
db.getMongo().getDBNames()

데이터베이스 기본

MongoDB는 데이터베이스와 컬렉션을 지연 생성합니다. 첫 문서를 삽입한 뒤에야 나타납니다. 'use mydb'는 컨텍스트만 바꾸며 데이터를 쓰기 전까지는 데이터베이스를 만들지 않습니다. show dbs는 비어 있는 데이터베이스를 나열하지 않습니다. dropDatabase는 모든 컬렉션과 데이터를 영구 삭제합니다.

mongodb
# show all databases
show dbs

# switch to (or create) a database
use mydb

# show the current database
db

# create is implicit: inserting into a
# non-existent collection creates both the
# collection and the database

# drop the current database
db.dropDatabase()

컬렉션

컬렉션은 SQL 테이블에 해당하며 문서를 담습니다. 첫 삽입 시 자동 생성되지만, createCollection으로 capped 같은 옵션을 지정할 수 있습니다(capped는 고정 크기 컬렉션으로 오래된 문서를 덮어씀. 로그에 유용). stats()는 저장 크기, 문서 수, 인덱스 상세를 보여 줍니다.

mongodb
# list collections in current database
show collections
db.getCollectionNames()

# create a collection explicitly with options
db.createCollection("users", {
  capped: true,
  size: 5242880,
  max: 5000
})

# rename a collection
db.users.renameCollection("accounts")

# drop a collection
db.users.drop()

# get collection stats
db.users.stats()

BSON 데이터 타입

BSON은 애플리케이션에 필수적인 추가 타입으로 JSON을 확장합니다. ObjectId(12바이트 고유 ID), ISODate, NumberDecimal(돈을 위한 정확한 소수. 부동소수점 반올림 회피), NumberLong(64비트 정수), BinData(바이너리) 등. 통화에는 NumberDecimal을 써야 고전적인 부동소수점 오류를 피할 수 있습니다.

mongodb
# MongoDB stores BSON (binary JSON) with rich types
{
  _id: ObjectId("65a1b2c3d4e5f6a7b8c9d0e1"),
  name: "Alice",                       // String
  age: 30,                             // Int32
  score: NumberLong(9007199254740992), // Int64
  price: NumberDecimal("19.99"),       // Decimal128 (exact money)
  active: true,                        // Boolean
  birthday: ISODate("1995-08-15"),     // Date
  tags: ["red", "blue"],               // Array
  meta: { views: 100 },                // Embedded document
  data: BinData(0, "aGVsbG8="),        // Binary
  id: UUID("...")                      // UUID
}

셸 헬퍼와 도움말

mongosh는 완전한 JavaScript를 지원하므로 셸에서 루프, 함수, 변수를 쓸 수 있습니다. .pretty()는 출력을 읽기 좋게 정렬합니다(mongosh에서 기본). load()는 셸 컨텍스트에서 .js 파일을 실행합니다. 반복적인 관리 스크립트에 유용합니다. db.collection.help()는 사용 가능한 모든 메서드를 나열합니다.

mongodb
# get help on database methods
db.help()

# get help on collection methods
db.users.help()

# list common shell commands
help

# pretty-print query results
db.users.find().pretty()

# print JSON in a compact form
db.users.find().toArray()

# execute a JavaScript file
mongosh --file script.js
load("script.js")
02

CRUD 연산

문서 삽입

_id(ObjectId)를 제공하지 않으면 MongoDB가 자동 생성합니다. _id는 컬렉션 내에서 고유해야 하며 중복 _id는 쓰기 오류를 일으킵니다. ordered:false를 쓰면 insertMany가 오류 이후에도 나머지 문서 삽입을 계속해 대량 로드 처리량을 높입니다.

mongodb
# insert a single document
db.users.insertOne({
  name: "Alice",
  email: "[email protected]",
  age: 30
})

# insert multiple documents
db.users.insertMany([
  { name: "Bob", age: 25 },
  { name: "Carol", age: 28 }
])

# insert with a custom _id
db.users.insertOne({ _id: 1, name: "Dave" })

# ordered insert (stops on error) vs unordered
db.users.insertMany(docs, { ordered: false })

Find / 문서 조회

find()는 커서를 반환하고(지연 평가), findOne()은 단일 문서 또는 null을 반환합니다. 프로젝션은 반환할 필드를 제어하며 포함과 제외를 섞을 수 없습니다(_id 제외). 1은 포함, 0은 제외입니다. countDocuments는 정확하고, 오래된 count()는 필터 카운트에 대해 폐기되었습니다.

mongodb
# find all documents
db.users.find()

# find with a filter
db.users.find({ age: 30 })
db.users.find({ "address.city": "NYC" })

# find one matching document
db.users.findOne({ name: "Alice" })

# projection: include/exclude fields
db.users.find({}, { name: 1, age: 1, _id: 0 })
db.users.find({}, { email: 0 })

# count matching documents
db.users.countDocuments({ age: { $gte: 18 } })

문서 업데이트

updateOne/updateMany는 업데이트 연산자($set, $inc 등)로 특정 필드를 수정합니다. replaceOne은 _id를 제외한 문서 전체를 교체합니다. upsert:true는 매칭이 없을 때 새 문서를 만듭니다. '생성 또는 갱신' 패턴에 유용합니다. 필드 갱신에는 항상 $set을 사용하세요. 맨 객체를 전달하면 문서를 교체합니다(레거시 동작).

mongodb
# update one document
db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 31, status: "active" } }
)

# update many documents
db.users.updateMany(
  { status: "pending" },
  { $set: { status: "active" } }
)

# replace an entire document (keeps _id)
db.users.replaceOne(
  { name: "Alice" },
  { name: "Alice", age: 32, city: "NYC" }
)

# upsert: insert if no match found
db.users.updateOne(
  { name: "Eve" },
  { $set: { age: 22 } },
  { upsert: true }
)

업데이트 연산자

업데이트 연산자는 문서 수준에서 필드를 원자적으로 수정합니다. $inc는 동시성 안전입니다(읽기-수정-쓰기 경쟁 없음). $min/$max는 새 값이 더 작거나 클 때만 갱신합니다. $currentDate는 '최종 수정' 타임스탬프에 편리합니다. 여러 연산자를 하나의 업데이트에서 조합할 수 있습니다.

mongodb
# $set and $unset
db.users.updateOne({n:"A"}, { $set: {age:30}, $unset: {temp:""} })

# $inc increments a numeric field
db.users.updateOne({n:"A"}, { $inc: {views: 1} })
db.users.updateOne({n:"A"}, { $inc: {balance: -50} })

# $rename a field
db.users.updateOne({n:"A"}, { $rename: {n: "name"} })

# $min / $max keep the smaller/larger value
db.users.updateOne({n:"A"}, { $min: {lowScore: 80} })

# $mul multiply the field value
db.users.updateOne({n:"A"}, { $mul: {price: 1.1} })

# $currentDate sets to current date
db.users.updateOne({n:"A"}, { $currentDate: {updatedAt: true} })

문서 삭제

deleteOne은 첫 매칭을, deleteMany는 모든 매칭을 삭제합니다. deleteMany({})는 인덱스를 유지한 채 컬렉션을 비웁니다(인덱스 정의를 보존하려면 drop+재생성보다 빠름). findOneAndDelete는 삭제된 문서를 원자적으로 반환합니다. 삭제는 되돌릴 수 없으므로 항상 필터를 신중히 작성하세요.

mongodb
# delete one matching document
db.users.deleteOne({ name: "Alice" })

# delete all matching documents
db.users.deleteMany({ status: "inactive" })

# delete all documents in a collection
db.users.deleteMany({})

# findAndDelete: return the deleted document
db.users.findOneAndDelete({ name: "Bob" })

# remove is deprecated, prefer deleteOne/deleteMany
db.users.remove({ name: "Bob" }, { justOne: true })

배열 업데이트 연산자

$push는 추가하고(중복 허용), $addToSet은 중복을 제거합니다. $pull은 조건에 맞는 요소를 제거합니다. 위치 연산자($)는 쿼리가 매칭한 첫 배열 요소를 가리키며, 인덱스를 모르는 채 특정 배열 요소를 갱신할 때 필수입니다. $[]는 모든 배열 요소를 갱신합니다.

mongodb
# $push append to an array
db.users.updateOne({n:"A"}, { $push: {tags: "new"} })

# $push with $each for multiple values
db.users.updateOne({n:"A"}, { $push: {tags: { $each: ["x","y"] } } })

# $addToSet adds only if not already present
db.users.updateOne({n:"A"}, { $addToSet: {tags: "x"} })

# $pull remove all matching array elements
db.users.updateOne({n:"A"}, { $pull: {tags: "x"} })

# $pop remove first (-1) or last (1) element
db.users.updateOne({n:"A"}, { $pop: {tags: 1} })

# update an array element by position
db.users.updateOne({}, { $set: {"tags.0": "first"} })
db.users.updateOne({"tags":"old"}, { $set: {"tags.$":"new"} })
03

문서 조회

비교 연산자

비교 연산자는 쿼리의 기초입니다. 같은 필드에 여러 $or 조건을 쓰는 것보다 $in이 훨씬 효율적입니다. 한 필드에 여러 연산자를 조합할 수 있습니다(예: 범위는 $gte와 $lte). $exists:true는 필드가 있는 문서를, $exists:false는 없는 문서를 찾습니다.

mongodb
# $eq equal (same as direct value)
db.products.find({ price: { $eq: 100 } })

# $ne not equal
db.products.find({ price: { $ne: 100 } })

# $gt, $gte, $lt, $lte
db.products.find({ price: { $gte: 50, $lte: 200 } })

# $in matches any value in an array
db.products.find({ category: { $in: ["books", "music"] } })

# $nin not in array
db.products.find({ category: { $nin: ["books"] } })

# $exists check field presence
db.products.find({ discount: { $exists: true } })

논리 연산자

암시적 AND(필터 안의 콤마)가 가장 흔하고 효율적입니다. 명시적 $and는 같은 필드에 여러 조건이 필요할 때만 쓰세요(같은 필드의 암시적 AND는 앞 조건을 덮어씁니다). $or는 별도의 인덱스 스캔 후 결과를 병합하므로 성능을 위해 $or의 필드에 인덱스를 거세요.

mongodb
# $and (explicit, useful for same-field conditions)
db.users.find({ $and: [
  { age: { $gte: 18 } },
  { age: { $lte: 65 } }
]})

# $or matches if ANY condition is true
db.users.find({ $or: [
  { status: "active" },
  { vip: true }
]})

# $nor matches if NO condition is true
db.users.find({ $nor: [{ status: "active" }]})

# $not inverts a condition
db.users.find({ age: { $not: { $gt: 18 } } })

# implicit AND (comma-separated)
db.users.find({ age: { $gte: 18 }, status: "active" })

요소 및 평가 연산자

$type은 BSON 타입으로 필터합니다(혼합 타입 필드에 유용). $regex는 'i'(대소문자 무시) 같은 옵션을 지원하지만, 접두어 앵커가 없는 정규식은 인덱스를 효율적으로 쓰지 못합니다. $expr은 문서 필드 간 비교를 가능하게 하는데 일반 연산자로는 불가능합니다. 인덱스를 우회할 수 있으니 $expr은 아껴 쓰세요.

mongodb
# $type filter by BSON data type
db.users.find({ age: { $type: "int" } })
db.users.find({ age: { $type: ["int", "double"] } })

# $regex regular expression match
db.users.find({ name: { $regex: "^Al", $options: "i" } })

# $mod modulo operation
db.users.find({ age: { $mod: [2, 0] } })  # even ages

# $expr compare fields within a document
db.orders.find({ $expr: { $gt: ["$total", "$budget"] } })

# $jsonSchema validate against a schema
db.users.find({ $jsonSchema: {
  required: ["name", "email"]
}})

배열 쿼리 연산자

$all은 지정한 모든 값을 포함하는 배열을 찾습니다(순서 무관). $elemMatch는 하나의 배열 요소가 여러 조건을 동시에 만족해야 할 때 필수입니다(일반 쿼리는 요소를 각각 매칭합니다). $size는 정확한 길이만 매칭하며 범위를 지원하지 않습니다. 대신 길이를 별도 필드로 미리 계산해 저장하세요.

mongodb
# $all: array contains ALL specified values
db.posts.find({ tags: { $all: ["mongo", "db"] } })

# $elemMatch: at least one element matches all conditions
db.students.find({ scores: { $elemMatch: {
  subject: "math", score: { $gte: 90 }
}}})

# $size: array of exact length
db.users.find({ tags: { $size: 3 } })

# match if array contains the value
db.posts.find({ tags: "mongo" })

# match a specific array index
db.users.find({ "scores.0": 95 })  # first score is 95

커서 메서드와 정렬

skip+limit으로 페이지네이션을 구현하지만 오프셋이 크면 skip은 느려집니다(건너뛴 문서를 모두 스캔). 깊은 페이지네이션에는 keyset 방식을 쓰세요. 정렬 필드가 마지막으로 본 값보다 큰 조건으로 쿼리합니다. sort()는 인덱스를 사용해 메모리 정렬을 피할 수 있으므로 큰 컬렉션에서는 정렬 필드에 항상 인덱스를 거세요.

mongodb
# limit and skip (pagination)
db.users.find().limit(10)
db.users.find().skip(20).limit(10)  # page 3

# sort: 1 ascending, -1 descending
db.users.find().sort({ age: 1, name: -1 })

# count results
db.users.find({active:true}).count()

# iterate the cursor in the shell
db.users.find().forEach(doc => print(doc.name))

# get a specific field's distinct values
db.users.distinct("city")
04

인덱싱

인덱스 생성

인덱스는 쿼리를 극적으로 빠르게 하지만 쓰기를 느리게 하고 디스크를 소비합니다. 단일 필드 인덱스는 그 필드의 어느 정렬 방향 쿼리든 지원합니다. 복합 인덱스는 최적 순서를 위해 ESR(Equality, Sort, Range) 규칙을 따릅니다. TTL 인덱스는 일정 시간 후 문서를 자동 삭제합니다. 세션과 로그에 완벽합니다.

mongodb
# create a single-field index
db.users.createIndex({ email: 1 })          # ascending
db.users.createIndex({ age: -1 })            # descending

# create a unique index
db.users.createIndex({ email: 1 }, { unique: true })

# create a compound index
db.users.createIndex({ lastName: 1, firstName: 1 })

# create a text index
db.posts.createIndex({ title: "text", body: "text" })

# create a TTL (time-to-live) index
db.sessions.createIndex({ createdAt: 1 },
  { expireAfterSeconds: 3600 })

# name an index explicitly
db.users.createIndex({ email: 1 }, { name: "email_idx" })

인덱스 조회와 관리

getIndexes는 모든 인덱스를 키와 옵션과 함께 나열합니다. hideIndex/unhideIndex는 인덱스를 실제로 드롭하지 않고 제거 영향을 테스트하게 합니다. 쿼리 플래너는 숨겨진 인덱스를 무시합니다. 성능이 그대로면 드롭해도 안전합니다. 인덱스 변경 전후로 항상 explain()을 실행하세요.

mongodb
# list all indexes on a collection
db.users.getIndexes()

# total index size in bytes
db.users.totalIndexSize()

# drop an index by name
db.users.dropIndex("email_1")

# drop all indexes except _id
db.users.dropIndexes()

# hide an index (test impact before dropping)
db.users.hideIndex("email_1")
db.users.unhideIndex("email_1")

# check if queries use indexes
db.users.find({email:"[email protected]"}).explain("executionStats")

특수 인덱스 타입

2dsphere 인덱스는 지리 쿼리를 지원합니다($near, $geoWithin). 해시 인덱스는 균등한 데이터 분포를 위한 해시 기반 샤딩에 쓰입니다. 와일드카드 인덱스($**)는 문서의 예측 불가능한/가변적인 필드 이름을 커버합니다. 다형적 데이터에 유용합니다. 부분 인덱스는 매칭 문서만 인덱싱해 일부만 조회할 때 공간을 절약합니다.

mongodb
# geospatial 2dsphere index (GeoJSON points)
db.places.createIndex({ location: "2dsphere" })
db.places.find({
  location: { $near: {
    $geometry: { type: "Point", coordinates: [-73.99, 40.73] },
    $maxDistance: 1000
  }}
})

# hashed index (for sharding)
db.users.createIndex({ user_id: "hashed" })

# wildcard index (index arbitrary field names)
db.products.createIndex({ "$**": 1 })

# partial index (only matching documents)
db.users.createIndex({ email: 1 },
  { partialFilterExpression: { active: true } })

Explain과 쿼리 플랜

explain()이 대표적인 성능 도구입니다. COLLSCAN(컬렉션 스캔)은 인덱스가 쓰이지 않았다는 뜻으로 큰 컬렉션에서는 경고 신호입니다. IXSCAN은 인덱스가 쓰였다는 뜻입니다. totalDocsExamined >> nReturned면 인덱스가 나쁩니다(적게 반환하려고 많이 검사). hint()는 플래너 선택을 테스트하려 특정 인덱스를 강제합니다.

mongodb
# explain a query (basic)
db.users.find({age:30}).explain()

# explain with execution stats (timing)
db.users.find({age:30}).explain("executionStats")

# key fields in the output:
#   winningPlan.stage    -> COLLSCAN (bad) or IXSCAN (good)
#   totalDocsExamined    -> should be close to nReturned
#   executionTimeMillis  -> query duration
#   indexUsed            -> which index was chosen

# force a specific index (testing)
db.users.find({age:30}).hint("age_1")
db.users.find({age:30}).hint({age:1})

인덱싱 베스트 프랙티스

ESR(Equality, Sort, Range) 규칙이 복합 인덱스 설계의 가장 중요한 원칙입니다. 등호 필터 필드를 먼저, 그다음 정렬 필드, 마지막 범위 필드. 커버드 쿼리(모든 필드가 인덱스에 있음)는 문서를 전혀 가져오지 않아 가장 빠른 쿼리입니다. 쓰지 않는 인덱스는 피하세요. 각각이 쓰기 오버헤드를 더합니다.

mongodb
# ESR rule: Equality, Sort, Range for compound indexes
# equality fields first, then sort, then range
db.orders.createIndex({
  status: 1,        # Equality  (filter)
  date: 1,          # Sort      (order)
  amount: 1         # Range     (comparison)
})

# avoid over-indexing: each index slows writes
db.orders.getIndexes().length

# covered query: index satisfies query without fetching doc
db.users.createIndex({ name: 1, email: 1 })
db.users.find({ name: "A" }, { _id: 0, name: 1, email: 1 })

# background index build (deprecated in 4.2+, builds don't block)
db.users.createIndex({ name: 1 })  # non-blocking by default
05

집계 프레임워크

집계 파이프라인 기본

집계 파이프라인은 문서를 스테이지 순서로 처리합니다. 파이프라인 앞쪽의 $match는 작업 집합을 줄이고(인덱스를 쓸 수 있음) $group은 SQL GROUP BY와 같습니다. $count는 $group + $project의 축약입니다. 순서가 중요합니다. 필터 → 그룹 → 정렬 → 제한 순으로.

mongodb
# a pipeline is an array of stages
db.orders.aggregate([
  { $match: { status: "shipped" } },
  { $group: { _id: "$customerId", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } },
  { $limit: 10 }
])

# each stage transforms documents and passes them
# to the next stage

# count documents
db.orders.aggregate([
  { $match: { status: "shipped" } },
  { $count: "shippedCount" }
])

$match, $project, $limit

$match는 항상 최대한 앞에 두세요. 이후 모든 스테이지의 문서를 줄이고 인덱스를 쓸 수 있습니다. $project는 문서를 재구성하고 표현식으로 새 필드를 계산합니다. $group 전에 $project로 필드 이름을 바꾸거나 계산하는 것이 흔합니다. $unset은 필드 제외의 축약입니다.

mongodb
# $match filters documents (like find)
{ $match: { status: "active", age: { $gte: 18 } } }

# $project reshapes documents (1 include, 0 exclude)
{ $project: { name: 1, _id: 0, "address.city": 1 } }

# $project with computed fields
{ $project: {
  fullName: { $concat: ["$first", " ", "$last"] },
  ageNextYear: { $add: ["$age", 1] }
}}

# $limit and $skip
{ $limit: 10 }
{ $skip: 20 }

# $unset removes fields (inverse of $project)
{ $unset: "tempField" }

$group과 누산기

$group이 집계의 핵심 스테이지입니다. _id가 그룹 키이며(null이면 모든 문서 집계) $push는 그룹별 값 배열을, $addToSet은 중복 없이 만듭니다. $first/$last는 그룹 내 문서 순서를 참조하므로 순서가 중요하면 $group 전에 $sort를 쓰세요. 메모리 한도는 스테이지당 100MB이며(큰 데이터셋에는 allowDiskUse 사용) 넘으면 오류가 납니다.

mongodb
# $group: group by a field and aggregate
{ $group: {
  _id: "$category",
  count: { $sum: 1 },
  totalRevenue: { $sum: "$amount" },
  avgPrice: { $avg: "$price" },
  minPrice: { $min: "$price" },
  maxPrice: { $max: "$price" },
  products: { $push: "$name" },     # array of values
  firstOrder: { $first: "$date" },
  lastOrder: { $last: "$date" }
}}

# group by multiple fields
{ $group: { _id: { category: "$cat", status: "$status" } } }

# group ALL documents together (_id: null)
{ $group: { _id: null, total: { $sum: "$amount" } } }

$lookup (조인)

$lookup은 왼쪽 외부 조인을 수행합니다. SQL의 LEFT JOIN과 같습니다. 조인된 데이터는 'as'로 명명된 배열 필드에 담깁니다. 파이프라인 형태로 조인된 문서를 필터·변형할 수 있습니다. $unwind는 배열 필드를 분해하고(배열 요소당 출력 문서 하나) $lookup 뒤에 결과를 평탄화할 때 자주 씁니다. MongoDB에서 조인은 내장 데이터보다 효율이 떨어집니다.

mongodb
# $lookup: join another collection (left outer join)
{ $lookup: {
  from: "orders",
  localField: "_id",
  foreignField: "customerId",
  as: "orders"
}}

# with pipeline (filtered/transformed join)
{ $lookup: {
  from: "orders",
  let: { custId: "$_id" },
  pipeline: [
    { $match: { $expr: { $eq: ["$customerId", "$$custId"] } } },
    { $project: { amount: 1, _id: 0 } }
  ],
  as: "recentOrders"
}}

# $unwind: flatten an array field into multiple docs
{ $unwind: "$orders" }

$unwind, $sort, $facet

$facet은 같은 입력에 여러 하위 파이프라인을 실행합니다. 한 쿼리로 top N, 카운트, 분해 등 여러 집계가 필요한 대시보드에 완벽합니다. $bucket은 값을 범위로 자동 분류합니다. preserveNullAndEmptyArrays를 준 $unwind는 배열이 비었거나 없는 문서도 유지해 파이프라인에서 데이터 유실을 피하게 합니다.

mongodb
# $unwind with preserveNullAndEmptyArrays
{ $unwind: {
  path: "$tags",
  preserveNullAndEmptyArrays: true
}}

# $sort within pipeline
{ $sort: { total: -1 } }

# $facet: run multiple pipelines in parallel
{ $facet: {
  "topCustomers": [{ $sort: {total:-1} }, { $limit: 5 }],
  "byCategory":   [{ $group: { _id: "$cat" } }],
  "totalCount":   [{ $count: "n" }]
}}

# $bucket: group into ranges automatically
{ $bucket: {
  groupBy: "$price",
  boundaries: [0, 50, 100, 500],
  default: "other",
  output: { count: { $sum: 1 } }
}}
07

트랜잭션

ACID 트랜잭션

멀티 문서 트랜잭션은 컬렉션에 걸쳐 ACID 보장을 제공합니다(레플리카 셋 또는 샤딩 클러스터 필요). 트랜잭션 안의 모든 연산에 세션을 전달하세요. commitTransaction은 변경을 영구화하고 가시화하며, abortTransaction은 모든 변경을 롤백합니다. 트랜잭션은 잠금을 쥐고 성능에 영향을 줄 수 있으니 짧게 유지하세요.

mongodb
# multi-document transaction (replica set required)
const session = db.getMongo().startSession()
session.startTransaction()

try {
  db.accounts.updateOne(
    { name: "Alice" }, { $inc: { balance: -100 } }, { session }
  )
  db.accounts.updateOne(
    { name: "Bob" }, { $inc: { balance: 100 } }, { session }
  )
  session.commitTransaction()
} catch (e) {
  session.abortTransaction()
  print("Transaction aborted: " + e)
} finally {
  session.endSession()
}

트랜잭션 읽기/쓰기 관심 수준

읽기 관심 수준(read concern)은 읽기의 신선함과 일관성을 제어합니다. 'snapshot'은 샤드에 걸쳐 트랜잭션적으로 일관된 뷰를 줍니다. 보고용에 이상적입니다. 쓰기 관심 수준(write concern)은 내구성을 제어합니다. w:majority는 복제 후 ack하므로(프라이머리 장애 조치에도 생존) j:true는 저널 플러시를 기다립니다. 높은 수준은 더 안전하지만 느립니다.

mongodb
# set transaction-level read/write concern
session.startTransaction({
  readConcern: { level: "snapshot" },
  writeConcern: { w: "majority", j: true, wtimeout: 5000 }
})

# read concern levels:
#   "local"      - sees latest local data (default)
#   "majority"   - committed, replicated to majority
#   "snapshot"   - consistent snapshot across shards

# write concern levels:
#   { w: 1 }             - ack from primary (default)
#   { w: "majority" }    - ack from majority of members
#   { j: true }          - wait for journal write

재시도 로직과 오류

MongoDB는 재시도 가능한 오류를 errorLabels로 표시합니다. TransientTransactionError는 트랜잭션 전체를 재시도, UnknownCommitResult는 커밋만 재시도입니다. 프로덕션 드라이버는 내장 재시도를 제공합니다. 트랜잭션은 가능한 한 멱등하게 설계하세요. 잠금을 쥐고 다른 연산을 막는 장기 트랜잭션은 피하세요.

mongodb
# transactions can fail with TransientTransactionError
# retry the whole transaction on these errors

function runTransaction(txnFunc) {
  while (true) {
    const session = db.getMongo().startSession()
    try {
      session.startTransaction()
      txnFunc(session)
      session.commitTransaction()
      return
    } catch (e) {
      session.abortTransaction()
      if (e.errorLabels &&
          e.errorLabels.includes("TransientTransactionError")) {
        continue  // retry
      }
      throw e   // non-retryable error
    } finally {
      session.endSession()
    }
  }
}

원자적 단일 문서 연산

단일 문서 연산은 기본적으로 원자적이므로 트랜잭션이 필요 없습니다. findOneAndUpdate/findOneAndReplace/findOneAndDelete는 문서를 원자적으로 반환합니다(순차 ID 생성에 좋음). 많은 워크로드에서 관련 데이터를 한 문서에 내장하고 원자적 연산자($inc, $push)를 쓰면 멀티 문서 트랜잭션 자체를 피할 수 있습니다.

mongodb
# single-document operations are ALWAYS atomic
db.counters.updateOne(
  { _id: "pageViews" },
  { $inc: { count: 1 } }
)

# findAndModify: atomically find & update, return the doc
db.sequences.findOneAndUpdate(
  { _id: "orderId" },
  { $inc: { seq: 1 } },
  { returnNewDocument: true }
)

# atomic upsert (create-or-increment)
db.counters.updateOne(
  { _id: "visits", date: "2025-01-01" },
  { $inc: { count: 1 } },
  { upsert: true }
)

# use $expr for conditional atomic updates
db.products.updateMany(
  { $expr: { $lt: ["$stock", "$reorderLevel"] } },
  { $set: { needsRestock: true } }
)

투 페이즈 커밋 (패턴)

투 페이즈 커밋 패턴은 네이티브 멀티 문서 트랜잭션 없이 분산 트랜잭션을 흉내 냅니다. 'pending' 상태를 추적해 전송 중 크래시가 나면 복구 프로세스가 재개하거나 롤백합니다. 가능하면 네이티브 트랜잭션을 쓰세요. 이 패턴은 복잡하고 오류가 나기 쉬워 주로 교육 및 레거시 목적으로 유지됩니다.

mongodb
# pattern for atomic transfers without transactions
# (pre-4.0 compatibility, or cross-system transfers)

# 1. create a pending transaction document
db.transactions.insertOne({
  _id: "t1", from: "Alice", to: "Bob", amount: 100, state: "pending"
})

# 2. debit source
db.accounts.updateOne(
  { name: "Alice", pendingTransactions: { $ne: "t1" } },
  { $inc: { balance: -100 }, $push: { pendingTransactions: "t1" } }
)

# 3. credit destination
db.accounts.updateOne(
  { name: "Bob", pendingTransactions: { $ne: "t1" } },
  { $inc: { balance: 100 }, $push: { pendingTransactions: "t1" } }
)

# 4. mark transaction done
db.transactions.updateOne({ _id: "t1" }, { $set: { state: "done" } })

# 5. clean up pending references
db.accounts.updateMany({},
  { $pull: { pendingTransactions: "t1" } })
08

데이터 모델링

내장 vs 참조

MongoDB 모델링의 핵심 결정입니다. 함께 접근되고 거의 바뀌지 않는 데이터는 내장하고, 크거나 공유되거나 독립 갱신되는 데이터는 참조하세요. 'has-a' 관계가 배타적일 때 내장합니다(사용자의 주소). 데이터가 재사용되면(많은 주문의 상품) 또는 무한 증가하면(수백만 로그 항목) 참조합니다.

mongodb
# EMBED: store related data in one document
db.users.insertOne({
  name: "Alice",
  addresses: [
    { city: "NYC", zip: "10001" },
    { city: "LA", zip: "90001" }
  ]
})
# Pros: single read, atomic update
# Cons: document size limit (16MB), data duplication

# REFERENCE: store IDs, join with $lookup
db.users.insertOne({ name: "Alice" })
db.orders.insertOne({
  customerId: ObjectId("..."),
  amount: 100
})
# Pros: no duplication, independent updates
# Cons: needs joins, more queries

일대다 관계

'소수' 관계는 내장합니다. '다수'는 자식에서 참조합니다(각 자식에 부모 ID). '매우 다수'(수백만)는 버킷 패턴을 씁니다. 자식 문서를 부모 소유 버킷(예: 월별)으로 묶어 문서 크기와 쿼리 속도의 균형을 맞춥니다. 무한 배열과 과도한 자식 문서를 모두 피합니다.

mongodb
# FEW: embed (e.g., a few addresses per user)
db.users.insertOne({
  name: "Alice",
  addresses: [{ city: "NYC" }, { city: "LA" }]
})

# MANY: reference with parent pointer
db.posts.insertOne({ title: "Hello", authorId: ObjectId("...") })

# VERY MANY: reference from parent (bucket pattern)
db.users.updateOne(
  { _id: userId },
  { $push: { postIds: postId } }   # beware 16MB limit
)

# BUCKET pattern for time series (thousands of items)
db.buckets.insertOne({
  ownerId: userId,
  date: "2025-01",
  measurements: [ {t: 1, v: 30}, {t: 2, v: 31} ]
})

다대다 관계

다대다는 쿼리 패턴과 데이터 크기로 접근을 고릅니다. 양방향 배열은 빠르지만 이중 유지보수가 필요합니다. 중간 컬렉션(매핑 테이블)이 가장 유연하고 확장성이 좋습니다. 관계 메타데이터(수강 신청일, 성적)를 저장할 수 있고 부모 문서 비대화를 피합니다.

mongodb
# option 1: arrays of ObjectIds on both sides
db.students.insertOne({ name: "Alice", courseIds: [c1, c2] })
db.courses.insertOne({ name: "Math", studentIds: [s1, s2] })

# option 2: one side references (smaller side)
db.students.insertOne({ name: "Alice", courseIds: [c1, c2] })

# option 3: mapping/junction collection
db.enrollments.insertOne({
  studentId: s1,
  courseId: c1,
  enrolledAt: ISODate(),
  grade: "A"
})

# query: find a student's courses
db.enrollments.find({ studentId: s1 })

스키마 설계 패턴

속성 패턴(Attribute Pattern)은 속성이 가변적인 엔티티(스펙이 다른 상품)를 다룹니다. 희소 필드를 피하고 동적 속성을 가능하게 합니다. 다형 패턴(Polymorphic Pattern)은 관련되지만 모양이 다른 데이터를 타입 판별자로 한 컬렉션에 저장합니다. 특이점 패턴(Outlier Pattern)은 예외적 문서(수백만 팔로워의 유명인)를 내장 대신 참조로 다룹니다.

mongodb
# ATTRIBUTE PATTERN: flexible attributes (e.g., products)
db.products.insertOne({
  name: "Laptop",
  attributes: [
    { k: "cpu", v: "i7" },
    { k: "ram", v: 16 }
  ]
})
# query: db.products.find({ "attributes.k": "cpu", "attributes.v": "i7" })

# POLYMORPHIC PATTERN: one collection, type discriminator
db.events.insertMany([
  { type: "click", url: "/home", userId: 1 },
  { type: "purchase", orderId: 99, total: 50 }
])

# OUTLIER PATTERN: cap large lists
db.users.updateOne({n:"A"}, { $set: { reviews: "see reviews collection" } })

스키마 검증

스키마 검증은 쓰기 시점에 문서 구조를 강제합니다. MongoDB식 고정 스키마입니다. validationLevel 'strict'는 모든 쓰기를, 'moderate'는 삽입과 전체 갱신만 검증합니다. validationAction 'error'는 잘못된 문서를 거부하고, 'warn'은 로그만 남기고 받아들입니다. 검증은 앱 수준 검증을 보완할 뿐 대체하지 않습니다.

mongodb
# add a JSON schema validator to a collection
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email"],
      properties: {
        name: { bsonType: "string", maxLength: 100 },
        email: { bsonType: "string", pattern: "^\S+@\S+$" },
        age: { bsonType: "int", minimum: 0, maximum: 150 },
        role: { enum: ["admin", "user", "guest"] }
      }
    }
  },
  validationLevel: "strict",
  validationAction: "error"
})

# add validation to an existing collection
db.runCommand({ collMod: "users", validator: { ... } })

# check existing validation rules
db.getCollectionInfos({ name: "users" })
09

레플리카 셋

레플리카 셋 기본

레플리카 셋은 고가용성과 읽기 확장을 제공합니다. 하나의 멤버만 프라이머리이고(쓰기 수용) 나머지는 비동기 복제합니다. 프라이머리가 실패하면 선거가 세컨더리를 자동 승격합니다. 홀수 투표 멤버(최소 3)가 선거 무승부를 피합니다. rs.status()는 각 멤버의 상태, 건강, 복제 지연을 보여 줍니다.

mongodb
# a replica set = 1 primary + N secondaries
# all writes go to the primary; secondaries replicate

# initiate a replica set
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "host1:27017" },
    { _id: 1, host: "host2:27017" },
    { _id: 2, host: "host3:27017" }
  ]
})

# check replica set status
rs.status()
rs.conf()

# step down the primary (force an election)
rs.stepDown(60)

# add a new member
rs.add("host4:27017")
rs.remove("host4:27017")

읽기 선호도

읽기 선호도는 일관성과 부하의 균형입니다. primary는 항상 최신 쓰기를 읽음을 보장합니다. secondary/secondaryPreferred는 프라이머리에서 읽기를 떼어내지만 데이터가 오래될 수 있습니다(복제 지연, 보통 밀리초). nearest는 지연을 최소화해 지리 분산 앱에 이상적입니다. 분석/보고 워크로드는 secondary 읽기를 쓰세요.

mongodb
# control where reads are routed
# primary (default) - always read from primary (strongest consistency)
db.users.find().readPref("primary")

# primaryPreferred - primary if available, else secondary
db.users.find().readPref("primaryPreferred")

# secondary - only secondaries (may be stale)
db.users.find().readPref("secondary")

# secondaryPreferred - prefer secondaries to offload primary
db.users.find().readPref("secondaryPreferred")

# nearest - lowest latency member
db.users.find().readPref("nearest")

# set in connection string
mongodb://host1:27017/mydb?replicaSet=rs0&readPreference=secondary

쓰기 관심 수준

쓰기 관심 수준은 속도와 안전의 절충입니다. w:1은 프라이머리가 쓰자마자 ack합니다(빠르지만 복제 전 프라이머리 크래시 시 데이터 유실 위험). w:majority는 쓰기가 복제됨을 보장해 단일 노드 장애에도 생존합니다(중요 데이터 권장). j:true는 디스크 저널 플러시를 기다립니다. 클러스터 수준에서 합리적인 기본값을 정하세요.

mongodb
# control how durable a write must be before ack
# w: 1 - primary acks (default, fastest, least safe)
db.users.insertOne(doc, { writeConcern: { w: 1 } })

# w: "majority" - majority of members confirmed
db.users.insertOne(doc, { writeConcern: { w: "majority" } })

# j: true - wait for journal flush (survives crash)
db.users.insertOne(doc, { writeConcern: { w: 1, j: true } })

# wtimeout - max wait time in ms
db.users.insertOne(doc, {
  writeConcern: { w: "majority", wtimeout: 5000 }
})

# set default write concern for the cluster
db.adminCommand({
  setDefaultRWConcern: { defaultWriteConcern: { w: "majority" } }
})

아비터와 선거

아비터는 데이터를 저장하지 않고 과반수를 이루는 한 표를 제공합니다. 2노드 배포에 유용하지만 세 번째 데이터 노드가 더 좋습니다. 우선순위 0 멤버는 절대 프라이머리가 되지 않습니다(전용 분석 또는 DR 노드에 좋음). 히든 멤버는 읽기 선호도 'nearest'에서 제외되며 백업에 이상적입니다. 지연 멤버는 뒤처져 있어 실수로 인한 삭제 복구를 가능하게 합니다.

mongodb
# an arbiter votes in elections but holds no data
rs.addArb("host5:27017")

# useful to break ties in even-member sets (e.g., 2 data + 1 arbiter)
# but prefer 3 data members for durability

# force a member to never become primary (priority 0)
rs.conf().members[1].priority = 0
rs.reconfig(rs.conf())

# hidden member: not visible to clients, used for analytics/backup
rs.conf().members[2].hidden = true
rs.conf().members[2].priority = 0
rs.reconfig(rs.conf())

# delayed member: lags behind (insurance against human errors)
rs.conf().members[3].secondaryDelaySecs = 3600
rs.conf().members[3].priority = 0

Oplog와 복제 내부

oplog(연산 로그)는 모든 쓰기를 기록하는 capped 컬렉션입니다. 세컨더리가 이 항목을 순서대로 적용해 복제합니다. 세컨더리가 oplog 윈도우를 벗어나 뒤처지면 전체 재동기화가 필요합니다. printReplicationInfo는 oplog의 시간 범위를, printSecondaryReplicationInfo는 각 세컨더리의 지연을 보여 줍니다. 큰 oplog는 긴 다운타임을 수용합니다.

mongodb
# the oplog is a capped collection of all writes
use local
db.oplog.rs.stats()
db.oplog.rs.find().sort({ $natural: -1 }).limit(5)

# each oplog entry is an idempotent operation
# { ts: ..., op: "i", ns: "mydb.users", o: { ... } }

# check replication lag
rs.printReplicationInfo()   # primary's oplog window
rs.printSecondaryReplicationInfo()  # each secondary's lag

# resync a stale secondary (full re-sync)
rs.syncFrom("host2:27017")

# change the oplog size (MongoDB 4.4+)
db.adminCommand({ replSetResizeOplog: 1, size: 16384 })  # MB
10

샤딩

샤딩 기본

샤딩은 컬렉션을 여러 샤드에 수평 확장합니다. 샤드 키가 데이터 분포를 결정하며 샤딩 후 불변입니다. 해시 샤딩은 균등 분포이고(ObjectId 같은 단조 증가 키에 좋음), 범위 샤딩은 목표 조회를 가능하게 하지만 핫스팟을 낳을 수 있습니다. 샤드 키는 신중히 고르세요. 나중에 쉽게 바꿀 수 없습니다.

mongodb
# sharding distributes data across multiple machines
# requires: config servers + shard replica sets + mongos router

# enable sharding on a database
sh.enableSharding("mydb")

# shard a collection (index on shard key required first)
sh.shardCollection("mydb.users", { userId: 1 })

# hash-based sharding (even distribution)
db.users.createIndex({ userId: "hashed" })
sh.shardCollection("mydb.users", { userId: "hashed" })

# view shard status
sh.status()
sh.addShard("rs1/host1:27017,host2:27017")

# balancer moves chunks between shards automatically
sh.startBalancer()
sh.stopBalancer()

샤드 키 선택

샤드 키가 샤딩에서 가장 중요한 결정입니다. 흔한 쿼리를 지원해야 합니다(샤드 키 없는 쿼리는 모든 샤드를 칩니다. scatter-gather). 높은 카디널리티는 이동 불가능한 점보 청크를 막습니다. 단조 키(타임스탬프, ObjectId)는 모든 삽입이 한 샤드를 치게 하므로 이런 경우 해시 샤딩을 쓰세요. 복합 키는 가장 선택적인 필드로 시작하세요.

mongodb
# GOOD shard key properties:
# - high cardinality (many distinct values)
# - low frequency (no single value dominates)
# - non-monotonic (avoids hot shards) OR use hashed

# hashed shard key (even distribution)
sh.shardCollection("mydb.logs", { _id: "hashed" })

# ranged shard key (enables targeted queries)
sh.shardCollection("mydb.events", { region: 1, date: 1 })

# compound shard key
sh.shardCollection("mydb.orders", { customerId: 1, orderId: 1 })

# check chunk distribution
db.getSiblingDB("config").chunks.find({ ns: "mydb.users" })

# see data distribution per shard
db.users.getShardDistribution()

존과 태그 인식 샤딩

존(태그 인식 샤딩)은 특정 데이터 범위를 특정 샤드로 라우팅합니다. 데이터 거주지 규정 준수(GDPR은 EU 데이터를 EU에 요구), 지역 근접성(빠른 지역 읽기), 하드웨어 계층(핫 데이터는 SSD, 콜드는 HDD)을 가능하게 합니다. 밸런서는 청크 이동 시 존 범위를 존중합니다. 먼저 샤드 태그를 정의한 뒤 태그 범위를 정의하세요.

mongodb
# tag shards by region (data locality / compliance)
sh.addShardTag("shard-us-east", "US")
sh.addShardTag("shard-eu", "EU")

# associate a key range with a tag
sh.addTagRange(
  "mydb.users",
  { region: "US", _id: MinKey },
  { region: "US", _id: MaxKey },
  "US"
)
sh.addTagRange(
  "mydb.users",
  { region: "EU", _id: MinKey },
  { region: "EU", _id: MaxKey },
  "EU"
)

# the balancer migrates tagged data to tagged shards
# useful for data residency (GDPR) and geo-locality

청크 관리

청크는 샤드 간 데이터 이동 단위입니다. 밸런서가 샤드 균형을 위해 청크를 자동 분할·이동합니다. 점보 청크는 크기 한도를 넘어 이동할 수 없으므로 좋은 샤드 키 카디널리티로 피하세요. 기본 128MB 청크 크기는 이동 속도와 오버헤드의 균형입니다. 수동 청크 작업은 루틴이 아니라 문제 해결용입니다.

mongodb
# chunks are ranges of shard key values
# default chunk size: 128MB (configurable)

# view chunks for a collection
db.getSiblingDB("config").chunks.find({ ns: "mydb.users" })

# manually move a chunk (testing)
sh.moveChunk("mydb.users", { userId: 100 }, "shard2")

# split a chunk at a specific value
sh.splitAt("mydb.users", { userId: 1000 })

# merge contiguous chunks
sh.mergeChunks("mydb.users",
  { userId: MinKey },
  { userId: 1000 }
)

# find chunks too large to migrate (jumbo chunks)
sh.status(true)   # verbose

샤딩 클러스터 구성 요소

샤딩 클러스터는 세 구성 요소입니다. config 서버(메타데이터, 레플리카 셋으로 배포), mongos 라우터(클라이언트가 연결하는 무상태 쿼리 라우터), 샤드(데이터 하위 집합을 담는 레플리카 셋 각각). 클라이언트는 절대 샤드에 직접 연결하지 않습니다. 샤드 제거는 남은 샤드로의 데이터 이동을 트리거하며 느린 과정이므로 모니터링해야 합니다.

mongodb
# config servers store metadata and routing info
# (deploy as a 3-member replica set)
# config server connection string:
# mongodb://cfg1:27019,cfg2:27019,cfg3:27019/config?replicaSet=cfgRS

# mongos is the query router (stateless, scale horizontally)
# clients connect to mongos, not shards directly
mongos --configdb cfgRS/cfg1:27019,cfg2:27019,cfg3:27019

# each shard is a replica set
sh.addShard("shardRS1/s1a:27017,s1b:27017,s1c:27017")
sh.addShard("shardRS2/s2a:27017,s2b:27017,s2c:27017")

# check cluster status
sh.status()

# remove a shard (migrates its data first)
db.adminCommand({ removeShard: "shardRS2" })
11

보안과 인증

인증과 사용자

인증은 신원을 확인합니다. auth를 켜기 전에 관리자 사용자를 만들어야 하며, 그렇지 않으면 잠겨 나옵니다. 내장 역할은 읽기 전용부터 풀 관리자까지 있습니다. 셸에서는 passwordPrompt()를 써서 평문 비밀번호가 히스토리에 남지 않게 하세요. 각 사용자는 한 데이터베이스에 속하지만 다른 데이터베이스의 역할도 가질 수 있습니다. 프로덕션에서는 TLS를 켜세요(net.tls.mode).

mongodb
# enable auth: start mongod with --auth
# or set security.authorization: "enabled" in config

# create the first admin user (before enabling auth)
use admin
db.createUser({
  user: "admin",
  pwd: passwordPrompt(),   // prompts securely
  roles: [ { role: "userAdminAnyDatabase", db: "admin" },
           { role: "readWriteAnyDatabase", db: "admin" } ]
})

# create a user for a specific database
use mydb
db.createUser({
  user: "appUser",
  pwd: passwordPrompt(),
  roles: [ { role: "readWrite", db: "mydb" } ]
})

# authenticate as a user
db.auth("appUser", "password")

내장 역할과 커스텀 역할

내장 역할이 흔한 경우를 커버하고, 커스텀 역할이 최소 권한을 가능하게 합니다. 권한은 리소스(데이터베이스/컬렉션)와 허용 행동(find, insert, update 등)의 쌍입니다. 필요한 최소한만 부여하세요. 보고 사용자는 특정 컬렉션의 'find'만 필요합니다. 커스텀 역할은 admin 데이터베이스에 저장되어 여러 사용자에서 재사용됩니다.

mongodb
# built-in roles:
#   read, readWrite, dbAdmin, dbOwner, userAdmin  (per database)
#   readAnyDatabase, readWriteAnyDatabase,         (all databases)
#   userAdminAnyDatabase, dbAdminAnyDatabase
#   root (superuser), clusterAdmin, backup, restore

# create a custom role with fine-grained privileges
db.createRole({
  role: "analyst",
  privileges: [
    { resource: { db: "mydb", collection: "reports" },
      actions: ["find"] },
    { resource: { db: "mydb", collection: "" },
      actions: ["listCollections"] }
  ],
  roles: []
})

# grant a role to a user
db.grantRolesToUser("appUser", [{ role: "analyst", db: "mydb" }])
db.revokeRolesFromUser("appUser", [{ role: "analyst", db: "mydb" }])

TLS/SSL 암호화

TLS는 전송 중 데이터를 암호화하며 프로덕션에서 필수입니다. requireTLS는 비TLS 연결을 거부합니다. 내부 PKI에서는 x.509 인증서 인증을 사용하세요(비밀번호 없음. 인증서 자체가 자격증명). $external 데이터베이스가 x.509 사용자를 저장합니다. 프로덕션에서는 항상 실제 CA(또는 내부 CA)를 쓰고, 자가 서명 인증서는 테스트 전용입니다.

mongodb
# enable TLS in mongod.conf
net:
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/mongodb/server.pem
    CAFile: /etc/mongodb/ca.pem

# connect with TLS and verify the server cert
mongosh "mongodb://host:27017/mydb" \
  --tls --tlsCAFile /etc/mongodb/ca.pem

# connect with a client certificate (x.509 auth)
mongosh "mongodb://host:27017/mydb" \
  --tls --tlsCertificateKeyFile client.pem \
  --tlsCAFile ca.pem \
  --authenticationMechanism MONGODB-X509 \
  --authenticationDatabase '$external'

# generate a self-signed cert for testing
openssl req -x509 -newkey rsa:4096 -nodes \
  -keyout server.key -out server.crt -days 365

네트워크와 감사

bindIp는 MongoDB가 리슨하는 네트워크 인터페이스를 제한합니다. MongoDB를 인터넷에 직접 노출하지 마세요(bindIp: 0.0.0.0 + 인증 없음은 셀 수 없는 침해를 낳았습니다). 감사(Enterprise 전용)는 규정 준수를 위해 보안 관련 연산을 로그합니다. 커뮤니티 에디션은 OS 수준 도구(auditd)나 앱 수준 로깅으로 대체할 수 있습니다.

mongodb
# restrict network interface in mongod.conf
net:
  bindIp: 127.0.0.1,10.0.0.5    # never 0.0.0.0 in production
  port: 27017

# enable auditing (enterprise feature)
auditLog:
  destination: file
  format: JSON
  path: /var/log/mongodb/audit.log
  filter: '{ atype: { $in: ["authenticate","createCollection","dropDatabase"] } }'

# view current authentication mechanisms
db.runCommand({ getCmdLineOpts: 1 })

# enable FIPS mode (government compliance)
setParameter:
  fipsMode: true

필드 수준 암호화 (CSFLE)

CSFLE는 민감 필드를 클라이언트에서 암호화해 서버, 백업, 로그에 평문이 남지 않게 합니다. 가장 강력한 데이터 보호입니다. 결정론적 암호화는 등호 쿼리를 지원하고, 랜덤 암호화는 더 안전하지만 조회할 수 없습니다. (드라이버 스키마를 통한) 자동 암호화는 앱 코드에 투명합니다. 암호화 키는 KMS에서 관리합니다(AWS KMS, 로컬 키 등).

mongodb
# Client-Side Field Level Encryption encrypts fields
# before sending to the server — server never sees plaintext

# define a data key in the key vault
const clientEncryption = db.getMongo().getClientEncryption()
const keyId = clientEncryption.createDataKey(
  "local", { keyAltNames: ["mainKey"] }
)

# encrypt a field explicitly
const ssn = clientEncryption.encrypt(
  keyId, "123-45-6789", "deterministic"
)

# store encrypted, query with encrypted value
db.patients.insertOne({ name: "Alice", ssn: ssn })
db.patients.find({
  ssn: clientEncryption.encrypt(keyId, "123-45-6789", "deterministic")
})

# automatic CSFLE uses a schema to encrypt per a JSON schema
# { encryptMetadata: { keyId: [keyId], algorithm: "AEAD_AES_256_CBC..." } }
12

백업과 복구

mongodump와 mongorestore

mongodump는 논리 백업(BSON 파일)을 만듭니다. 이식성은 있지만 큰 데이터셋에는 느리고 --oplog 없이는 컬렉션 간 시점 일관성이 없습니다. --drop은 복원 전 기존 컬렉션을 드롭합니다. --archive + --gzip은 단일 압축 파일을 만듭니다. 큰 프로덕션 백업에는 mongodump 대신 파일시스템 스냅샷이나 Percona Backup을 선호하세요.

mongodb
# dump an entire database
mongodump --db=mydb --out=/backup/$(date +%F)

# dump a single collection
mongodump --db=mydb --collection=users --out=/backup

# dump with a query filter
mongodump --db=mydb --collection=logs \
  --query='{"date":{"$gte":{"$date":"2025-01-01T00:00:00Z"}}}'

# compress the output archive
mongodump --archive=/backup/full.gz --gzip

# restore from a dump
mongorestore --db=mydb --drop /backup/2025-01-01/mydb
mongorestore --archive=/backup/full.gz --gzip

mongoexport와 mongoimport

mongoexport/mongoimport는 JSON/CSV를 다룹니다. 다른 시스템과의 데이터 교환용이며 백업용이 아닙니다(ObjectId와 Date 정밀도 같은 BSON 타입이 손실됨). 백업에는 mongodump를 쓰세요. CSV 내보내기는 스프레드시트와 BI 도구에 좋습니다. 예측 가능한 CSV 열 순서를 위해 항상 --fields를 지정하세요. JSON 내보내기는 기본적으로 줄당 문서 하나입니다(--jsonArray로 단일 배열).

mongodb
# export to JSON (human-readable)
mongoexport --db=mydb --collection=users \
  --out=users.json

# export to CSV
mongoexport --db=mydb --collection=users \
  --type=csv --fields=name,email,age --out=users.csv

# export with a query filter
mongoexport --db=mydb --collection=users \
  --query='{"status":"active"}' --out=active.json

# import from JSON
mongoimport --db=mydb --collection=users --file=users.json

# import from CSV with header row
mongoimport --db=mydb --collection=users \
  --type=csv --headerline --file=users.csv

파일시스템 스냅샷

파일시스템 스냅샷은 큰 데이터셋에서 가장 빠른 백업 방법입니다. 전체 데이터 디렉터리를 일관되게 포착합니다. fsyncLock이 잠시 쓰기를 막고 디스크로 플러시해 스냅샷이 일관되게 합니다. 스냅샷은 데이터 크기와 무관하게 거의 즉시입니다. 복원은 파일 복사만큼 단순하며 mongorestore보다 훨씬 빠릅니다. LVM, ZFS, 클라우드 블록 스토리지(EBS 스냅샷)에서 가장 잘 동작합니다.

mongodb
# snapshot the dbPath volume for a consistent backup
# 1. flush writes to disk and lock (brief)
db.fsyncLock()

# 2. take a filesystem snapshot (LVM, ZFS, EBS, etc.)
lvcreate --snapshot --size 1G --name mongosnap /dev/vg/data

# 3. unlock the database
db.fsyncUnlock()

# 4. mount the snapshot and copy or back it up
mount /dev/vg/mongosnap /mnt/snap
rsync -a /mnt/snap/ /backup/

# restore: stop mongod, replace dbPath, start mongod
# (fastest restore method for large datasets)

시점 복구 (oplog)

시점 복구(PITR)는 특정 시점의 데이터베이스 상태를 재구성합니다. 실수로 인한 삭제나 잘못된 마이그레이션 후 필수입니다. --oplog로 정기 기저 백업을 받고, 원하는 타임스탬프까지 oplog를 재생합니다(--oplogLimit은 나쁜 연산 직전에서 멈춤). PITR에는 레플리카 셋이 필요합니다(oplog는 레플리카 셋 멤버에만 존재).

mongodb
# 1. take a base backup (snapshot or mongodump --oplog)
mongodump --archive=/backup/base.gz --oplog --gzip

# 2. note the time of the accident
# 3. replay the oplog up to just before the error

# dump the oplog from a secondary
mongodump --db=local --collection=oplog.rs \
  --query='{"ts":{"$gt":{"$timestamp":{"t":1700000000,"i":1}}}}' \
  --out=/oplog_dump

# restore the base backup, then replay oplog
mongorestore --archive=/backup/base.gz --oplogReplay \
  --oplogLimit=1700000123:1   # stop before this timestamp

# for a running replica set, use mongorestore --oplogReplay
# with a BSON oplog file

Atlas 백업과 클라우드 옵션

MongoDB Atlas는 시점 복구가 가능한 관리형 지속 백업을 제공합니다. 클라우드 배포에서 가장 간단합니다. Percona Backup for MongoDB(PBM)는 셀프 호스팅 클러스터용 선도적 오픈소스 백업 도구로, 레플리카 셋과 샤딩 클러스터에 걸쳐 물리 백업과 PITR을 지원합니다. 복원 절차를 항상 테스트하세요. 복원할 수 없는 백업은 백업이 아닙니다.

mongodb
# MongoDB Atlas: continuous backups with PITR
# configured via UI or Atlas CLI:
atlas backups policies create [clusterId] ...

# on-demand snapshot
atlas backups snapshots create [clusterId] \
  --description "pre-migration" \
  --retentionDays 7

# restore an Atlas snapshot
atlas backups restores start [clusterId] \
  --snapshotId [snapId] \
  --deliveryType automated \
  --targetClusterName [target]

# Percona Backup for MongoDB (PBM) — open source
pbm backup --type=physical
pbm restore [snapshotName]
pbm pitr restore --time "2025-01-15T14:30:00"
13

성능과 최적화

느린 쿼리 프로파일링

데이터베이스 프로파일러는 slowms(기본 100ms)보다 느린 연산을 system.profile(capped 컬렉션)에 기록합니다. 레벨 2는 모든 것을 기록합니다. 디버깅에 유용하지만 성능에 영향을 줍니다. 비효율 쿼리를 찾으려 millis(소요 시간), nreturned(반환 문서 수), docsExamined을 보세요. 끝나면 프로파일링을 끄세요.

mongodb
# enable the database profiler
# levels: 0=off, 1=slow ops only, 2=all ops
db.setProfilingLevel(1, { slowms: 100 })

# view profiled operations
db.system.profile.find().sort({ ts: -1 }).limit(5)

# find the slowest operations
db.system.profile.find({ millis: { $gt: 1000 } })
  .sort({ millis: -1 })

# profile a specific collection
db.system.profile.find({ ns: "mydb.users" })

# get current profiling level
db.getProfilingStatus()

# clear the profile collection
db.system.profile.drop()

explain() 심화

explain()이 대표적인 튜닝 도구입니다. COLLSCAN은 전체 컬렉션 스캔이므로 인덱스를 추가하세요. docsExamined 대 nReturned 비율이 핵심 효율 지표입니다. 10개를 반환하려고 10000개 문서를 검사한다면 인덱스가 나쁩니다. allPlansExecution은 플래너가 왜 그 플랜을 골랐는지 보여 줍니다. 쿼리의 등호, 정렬, 범위 필드에 인덱스를 거세요(ESR 규칙).

mongodb
# three verbosity modes
db.users.find({age:30}).explain("queryPlanner")     # plan only
db.users.find({age:30}).explain("executionStats")    # + timing
db.users.find({age:30}).explain("allPlansExecution") # + rejected plans

# key metrics to check:
#   winningPlan.stage: COLLSCAN (bad) vs IXSCAN (good)
#   totalKeysExamined: index entries scanned
#   totalDocsExamined: documents fetched
#   nReturned: documents returned
#   executionTimeMillis: total time
#   works: number of work units

# ideal ratio: docsExamined ≈ nReturned
# if docsExamined >> nReturned -> missing or bad index

워킹 셋과 메모리

성능은 워킹 셋(자주 접근되는 데이터)이 RAM에 들어가는 데 달려 있습니다. wiredTiger.cache의 'pages read into cache'가 높으면 디스크를 치는 중이므로 RAM을 더하거나 스캔을 줄일 인덱스를 추가하세요. mongotop은 I/O가 뜨거운 컬렉션을, mongostat은 쿼리/삽입/갱신 비율과 faults를 보여 줍니다. compact는 삭제/갱신된 문서가 낭비한 디스크 공간을 회수합니다.

mongodb
# check the working set size
db.serverStatus().wiredTiger.cache
# look at: "maximum bytes configured", "current bytes"
#          "pages requested from disk" vs "pages read into cache"

# check storage stats
db.stats()
db.users.stats()
db.users.totalSize()   # data + index size in bytes

# mongotop: time spent reading/writing per collection
mongotop 30   # every 30 seconds

# mongostat: live server stats
mongostat --rowcount 10  # 10 iterations

# compact a collection (reclaims disk, blocks writes pre-4.4)
db.runCommand({ compact: "users" })

커넥션 풀링

MongoDB 연결은 각각 서버 메모리를 소비하며 수천 개의 연결은 성능을 저하시킵니다. 커넥션 풀링을 쓰고(드라이버가 재사용 풀을 유지) 부하에 맞춰 maxPoolSize를 조정하세요(50~100이 전형). 앱 전체에서 MongoClient 하나를 공유하고 요청마다 만들지 마세요. 로드 밸런서 뒤에서 오래된 연결을 재활용하려 maxIdleTimeMS를 설정하세요.

mongodb
# each connection consumes memory (~1MB) on the server
# limit connections in the driver's connection string
mongodb://host:27017/mydb?maxPoolSize=50

# Node.js driver example
const { MongoClient } = require("mongodb")
const client = new MongoClient(uri, {
  maxPoolSize: 50,        // max connections
  minPoolSize: 5,         // keep-alive connections
  maxIdleTimeMS: 30000,   // close idle conns after 30s
  serverSelectionTimeoutMS: 5000
})

# view current connections on the server
db.serverStatus().connections
# { current: 120, available: 880, totalCreated: 200 }

대량 쓰기와 배치 크기

대량 쓰기는 연산을 한 번의 왕복으로 묶어 개별 연산보다 훨씬 빠릅니다. unordered:true가 처리량을 최대화합니다(오류를 건너뛰고 샤딩 클러스터에서 병렬화). 큰 임포트는 메모리와 왕복의 균형을 위해 1000~5000 문서 단위로 배치하세요. ordered:false를 준 insertMany가 데이터 로드의 가장 빠른 방법입니다.

mongodb
# ordered bulk write (stops on first error)
db.users.bulkWrite([
  { insertOne: { document: { name: "A" } } },
  { updateOne: { filter: {n:"B"}, update: {$set:{age:1}} } },
  { deleteOne: { filter: { n: "C" } } }
], { ordered: true })

# unordered bulk write (continues on errors, faster)
db.users.bulkWrite(ops, { ordered: false })

# insertMany is a bulk insert — batch large loads
const docs = Array.from({length: 100000}, (_,i) => ({ i }))
const batch = 1000
for (let i = 0; i < docs.length; i += batch) {
  db.big.insertMany(docs.slice(i, i + batch), { ordered: false })
}
14

Change Streams

변경 감시

Change streams은 oplog를 따라가며 앱이 데이터 변경에 실시간 반응하게 합니다. 각 이벤트는 연산 유형, 전체 문서(fullDocument 옵션을 준 삽입/갱신), 재개 토큰을 포함합니다. 재시작 후 이벤트를 빠뜨리거나 중복 없이 재개하려면 재개 토큰을 저장하세요. 레플리카 셋 또는 샤딩 클러스터가 필요합니다.

mongodb
# open a change stream on a collection
const stream = db.users.watch()

# process change events (Node.js driver)
stream.on("change", (event) => {
  console.log(event.operationType)  // insert|update|delete|replace
  console.log(event.fullDocument)   // the new document
  console.log(event.documentKey)    // the _id
  console.log(event.updateDescription)  // updated fields
})

# resume token enables restart from last position
const token = stream.resumeToken
// store token, then resume later:
const stream2 = db.users.watch([], { resumeAfter: token })

# close the stream
stream.close()

변경 이벤트 필터링

집계 파이프라인으로 change stream을 필터하면 매칭 이벤트만 앱에 도달해 노이즈가 줄어듭니다. 기본적으로 갱신은 전체 문서가 아니라 바뀐 필드만 포함합니다. fullDocument:'updateLookup'은 현재 문서를 가져옵니다(이벤트마다 추가 쿼리). fullDocumentBeforeChange(6.0+)는 변경 전 문서를 포함해 감사 로그에 유용합니다.

mongodb
# filter with an aggregation pipeline
const stream = db.users.watch([
  { $match: { operationType: "update" } },
  { $match: { "updateDescription.updatedFields.status": "active" } },
  { $project: { fullDocument: 1, documentKey: 1 } }
])

# watch specific operations
{ $match: { operationType: { $in: ["insert", "update"] } } }

# full document lookup on update (fetches current doc)
db.users.watch([], {
  fullDocument: "updateLookup"   // include latest doc on updates
})

# fullDocumentBeforeChange (MongoDB 6.0+)
db.users.watch([], {
  fullDocumentBeforeChange: "whenAvailable"
})

데이터베이스/클러스터 단위 Change Stream

Change stream은 단일 컬렉션, 전체 데이터베이스, 전체 클러스터를 감시할 수 있습니다. 데이터베이스와 클러스터 스트림은 각 이벤트에 네임스페이스(ns)를 포함해 어디서 변경이 일어났는지 알려 줍니다. startAtOperationTime으로 oplog의 특정 시점부터 변경을 재생하세요. 다운타임 후 누락 이벤트 복구나 백필에 유용합니다.

mongodb
# watch all collections in a database
const stream = db.watch()

# watch all databases in a cluster
const stream = client.watch()

# events include the ns (namespace) field
stream.on("change", (e) => {
  console.log(e.ns.db + "." + e.ns.coll)
  console.log(e.operationType)
})

# useful for audit logging, cache invalidation,
# cross-system sync, and real-time analytics

# start at a specific timestamp
db.users.watch([], {
  startAtOperationTime: Timestamp(1700000000, 1)
})

재개 토큰과 신뢰성

재개 토큰은 at-least-once 전달을 보장합니다. 각 이벤트를 처리한 뒤 토큰을 영속화하면 재시작 시 정확히 마지막 지점에서 재개합니다. resumeAfter와 startAfter가 비슷하며, startAfter는 컬렉션 무효화 이벤트(drop 등) 이후에도 동작합니다. 항상 오류를 처리하고 마지막 토큰으로 재연결하세요. 토큰은 불투명하므로 블랙박스로 취급하세요.

mongodb
# each event has a resume token (_id)
stream.on("change", (e) => {
  saveToStore(e._id)        // persist the token
  processEvent(e)
})

# after a restart, resume from the last token
const lastToken = loadFromStore()
const stream = db.users.watch([], {
  resumeAfter: lastToken     // resume after this event
})

# alternative: start after a cluster time
db.users.watch([], { startAfter: lastToken })

# handle errors and reconnect
stream.on("error", (err) => {
  console.error("stream error", err)
  // reconnect with the last saved token
})

# the token is opaque — store it, don't parse it

Change Stream 사용 사례

Change stream은 실시간 아키텍처를 구동합니다. 캐시 무효화(오래된 캐시 항목 삭제), 실시간 알림(WebSocket 푸시), 감사 로깅(규정 준수를 위해 모든 변경 기록), ETL/동기화(Elasticsearch, 데이터 웨어하우스, 다른 시스템으로 복제). 수동 폴링과 트리거를 깔끔한 반응형 이벤트 구동 모델로 대체합니다.

mongodb
# 1. Cache invalidation: clear cache when data changes
stream.on("change", (e) => {
  redis.del("user:" + e.documentKey._id)
})

# 2. Real-time notifications: push to WebSocket clients
stream.on("change", (e) => {
  io.emit("user-updated", e.fullDocument)
})

# 3. Audit log: record all changes to a separate store
stream.on("change", (e) => {
  auditLog.insertOne({
    op: e.operationType,
    doc: e.fullDocument,
    at: new Date()
  })
})

# 4. ETL: sync to a search index or warehouse
stream.on("change", async (e) => {
  await elasticsearch.index(e.fullDocument)
})
15

관리와 도구

서버 상태와 모니터링

serverStatus()가 대표적인 모니터링 원천입니다. 연결, opcounters, 캐시 히트율, 복제 지연을 추적하세요. currentOp는 실행 중인 연산을 보여 주고 killOp는 opid로 장기 쿼리를 종료합니다. Prometheus, Datadog, Atlas 같은 모니터링 에이전트로 이 지표를 지속 수집하세요. 핵심 알림: 한도에 근접한 연결 수, 떨어지는 캐시 히트율, 치솟는 복제 지연.

mongodb
# overall server status
db.serverStatus()

# key metrics to monitor:
db.serverStatus().connections       # active/idle connections
db.serverStatus().opcounters         # queries/inserts/updates/sec
db.serverStatus().wiredTiger.cache   # cache hit ratio (aim >95%)
db.serverStatus().metrics.document   # docs inserted/returned/deleted
db.serverStatus().repl               # replication state

# current operations (find long-running ops)
db.currentOp({ secs_running: { $gte: 5 } })

# kill a long-running operation
db.killOp(opid)

# host info (CPU, OS, memory)
db.hostInfo()

데이터베이스와 컬렉션 통계

stats()는 저장 상세를 보여 줍니다. dataSize(논리), storageSize(물리. WiredTiger 압축 후로 보통 50~80% 작음), indexSize. estimatedDocumentCount는 즉시(컬렉션 메타데이터 기반)이지만 근사이고, countDocuments({})는 정확하지만 스캔합니다. 대시보드에는 근사 카운트, 청구에는 정확한 카운트를 쓰세요. 용량 계획을 위해 저장 성장 추세를 모니터링하세요.

mongodb
# database-level stats
db.stats()
db.stats(1024*1024)   # in MB

# collection-level stats
db.users.stats()
db.users.dataSize()       # uncompressed data size
db.users.storageSize()    # on-disk size (with compression)
db.users.totalIndexSize() # total index size
db.users.totalSize()      # data + indexes

# count documents (accurate, may be slow)
db.users.countDocuments({})

# estimated count (fast, from metadata)
db.users.estimatedDocumentCount()

# list collections with sizes
db.runCommand({ listCollections: 1 })

Compact와 Repair

WiredTiger는 해제된 디스크 공간을 재사용하므로 compact는 드뭅니다. 컬렉션의 큰 비율을 삭제한 뒤에만 필요합니다. compact는 컬렉션 연산을 막습니다(4.4 미만) 또는 온라인으로 실행됩니다(4.4+). repairDatabase는 모든 데이터를 다시 쓰는 파괴적 최후 수단이며 항상 먼저 백업하세요. 레플리카 셋의 공간 회수는 세컨더리를 재동기화하세요(데이터 삭제 후 재복제).

mongodb
# compact: reclaim disk space from deleted/updated docs
# (WiredTiger reuses freed space, so rarely needed)
db.runCommand({ compact: "users" })

# fullDatabase compact (compact every collection)
db.getCollectionNames().forEach(c => {
  db.runCommand({ compact: c })
})

# repairDatabase (legacy, rewrites all data — last resort)
# Stops the server! Back up first.
mongod --repair --dbpath /data/db

# check data integrity (validates BSON)
db.users.validate({ full: true })

# reclaim space by re-syncing a secondary instead
# (safer than repair on a running primary)

mongotop과 mongostat

mongostat은 서버 부하의 실시간 개요를 줍니다(삽입, 쿼리, 캐시 사용, 연결). MongoDB의 top/vmstat 같은 것입니다. mongotop은 어느 컬렉션이 가장 많은 I/O 시간을 소비하는지 보여 주며 뜨거운 컬렉션 찾기에 귀중합니다. 둘 다 MongoDB에 번들됩니다. 프로덕션 모니터링에서는 mongod 로그와 serverStatus 지표를 모니터링 시스템으로 보내 역사 분석하세요.

mongodb
# mongostat: live server stats (like vmstat for MongoDB)
mongostat
mongostat --host=host:27017 --rowcount 10
# columns: insert/query/update/delete/getmore/command
#          dirty (cache %), used (cache %), conn, time

# mongotop: time spent per collection (read/write)
mongotop
mongotop 30          # every 30 seconds
mongotop --host=host:27017

# columns: ns (namespace), total/read/write time (ms)
# helps identify which collections are I/O hot

# log slow queries in the mongod log
# set in mongod.conf:
# operationProfiling:
#   mode: slowOp
#   slowOpThresholdMs: 100

설정과 시작

프로덕션 MongoDB는 설정 파일(YAML의 mongod.conf)로 실행합니다. 핵심 설정: cacheSizeGB는 WiredTiger의 RAM을 제한하고(기본은 RAM의 50%. 공유 서버에서는 명시적으로 설정), bindIp는 네트워크 접근을 제한하고, authorization은 인증을 켜고, replSetName/clusterRole은 복제/샤딩을 켭니다. mongod.conf를 항상 검토하고 버전 관리하세요. serverCmdLineOpts가 활성 설정을 보여 줍니다.

mongodb
# start mongod with a config file
mongod --config /etc/mongod.conf

# typical mongod.conf (YAML)
storage:
  dbPath: /var/lib/mongodb
  wiredTiger:
    engineConfig:
      cacheSizeGB: 4        # limit RAM usage
  journal:
    enabled: true
net:
  port: 27017
  bindIp: 127.0.0.1
security:
  authorization: enabled
replication:
  replSetName: rs0
sharding:
  clusterRole: shardsvr

# view current configuration
db.serverCmdLineOpts()
db.runCommand({ getCmdLineOpts: 1 })
16

드라이버와 통합

Node.js 드라이버

Node.js 드라이버는 async/await 기반이며 완전한 ES6+를 지원합니다. 항상 커넥션 풀링을 쓰세요(앱당 MongoClient 하나, 재사용). 커서는 비동기 이터러블이므로 for-await-of로 전체 문서를 메모리에 올리지 않고 순회할 수 있습니다. 종료 시 클라이언트를 닫으세요. 드라이버는 트랜잭션, change stream, 모든 집계 기능을 지원합니다.

mongodb
const { MongoClient } = require("mongodb")

const client = new MongoClient(
  "mongodb://localhost:27017",
  { maxPoolSize: 50 }
)

async function main() {
  await client.connect()
  const db = client.db("mydb")
  const users = db.collection("users")

  // insert
  await users.insertOne({ name: "Alice", age: 30 })

  // find with a cursor
  const cursor = users.find({ age: { $gte: 18 } })
  for await (const doc of cursor) {
    console.log(doc.name)
  }

  // update
  await users.updateOne(
    { name: "Alice" },
    { $inc: { age: 1 } }
  )
}

main().finally(() => client.close())

Python 드라이버 (PyMongo)

PyMongo는 공식 Python 드라이버입니다. 동기식이며, 비동기는 Motor(asyncio)나 Beanie(ODM)를 사용하세요. PyMongo 딕셔너리는 평범한 Python dict이며 특별한 객체가 필요 없습니다. 집계 파이프라인은 dict의 리스트입니다. 컨텍스트 매니저 트랜잭션 패턴이 자동 커밋/중단을 보장합니다. 항상 커넥션 풀링을 쓰세요(기본 MongoClient가 연결을 풀링).

mongodb
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017")
db = client["mydb"]
users = db["users"]

# insert
users.insert_one({"name": "Alice", "age": 30})

# find
for doc in users.find({"age": {"$gte": 18}}).sort("age", -1):
    print(doc["name"])

# update
users.update_one(
    {"name": "Alice"},
    {"$inc": {"age": 1}}
)

# aggregation
pipeline = [
    {"$group": {"_id": "$city", "count": {"$sum": 1}}},
    {"$sort": {"count": -1}}
]
for doc in users.aggregate(pipeline):
    print(doc)

# use a context manager for transactions
with client.start_session() as session:
    with session.start_transaction():
        users.update_one({"n":"A"}, {"$inc":{"bal":-100}}, session=session)
        users.update_one({"n":"B"}, {"$inc":{"bal":100}}, session=session)

드라이버에서 인덱스 생성

인덱스는 앱의 셋업/마이그레이션 스크립트에서 만드세요. 요청마다 만들지 마세요. createIndexes(복수형)는 한 번의 호출로 여러 인덱스를 만듭니다. 프로덕션에서 큰 컬렉션의 인덱스 빌드는 느릴 수 있지만, MongoDB 4.2+는 기본적으로 논블로킹 인덱스 빌드를 합니다. 인덱스 생성 스크립트를 스키마 마이그레이션과 함께 버전 관리하세요.

mongodb
// Node.js: create indexes
await db.collection("users").createIndex({ email: 1 }, { unique: true })
await db.collection("users").createIndex({ name: "text" })

// Python
users.create_index([("email", 1)], unique=True)
users.create_index([("name", "text")])

// list indexes
const indexes = await db.collection("users").indexes()

// drop an index
await db.collection("users").dropIndex("email_1")

// create indexes in bulk
await db.collection("orders").createIndexes([
  { key: { customerId: 1 } },
  { key: { status: 1, date: -1 }, name: "status_date" }
])

연결 문자열 옵션

연결 문자열은 모든 클라이언트 설정을 쿼리 파라미터로 실어 나릅니다. mongodb+srv는 DNS SRV 레코드로 호스트를 찾습니다. Atlas가 이 형식을 쓰며, 연결 문자열을 단순화하고 노드 변화 시 자동 갱신합니다. retryWrites=true(최신 드라이버 기본)는 네트워크 블립 후 멱등 쓰기를 자동 재시도합니다. 매달린 연결을 피하려 합리적인 타임아웃을 설정하세요.

mongodb
# standard connection string
mongodb://user:pass@host1:27017,host2:27017/mydb?replicaSet=rs0

# common options (as query params):
#   replicaSet=rs0            - replica set name
#   readPreference=secondary  - route reads to secondaries
#   readConcernLevel=majority - read committed data
#   w=majority                - write concern
#   journal=true              - wait for journal flush
#   maxPoolSize=50            - max connections
#   connectTimeoutMS=5000     - connection timeout
#   socketTimeoutMS=30000     - socket timeout
#   authSource=admin          - db for credentials
#   tls=true                  - enable TLS
#   retryWrites=true          - retry on network errors

# SRV connection string (Atlas, uses DNS)
mongodb+srv://user:[email protected]/mydb

ODM과 고수준 라이브러리

ODM(Object Document Mapper)은 스키마, 검증, 고수준 API를 더합니다. Mongoose(Node.js)가 가장 인기 있으며 MongoDB에 기본 없는 구조를 강제합니다. Beanie가 선도적 비동기 Python ODM입니다. ODM은 빠른 개발과 팀 일관성에 좋지만 오버헤드를 더하고 MongoDB의 능력을 가릴 수 있습니다. 성능이 중요한 앱은 원시 드라이버를 사용하세요.

mongodb
// Mongoose (Node.js ODM with schemas)
const mongoose = require("mongoose")
const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  age: { type: Number, min: 0 }
})
const User = mongoose.model("User", userSchema)
await User.create({ name: "Alice", age: 30 })
await User.find({ age: { $gte: 18 } })

# Beanie (Python async ODM)
from beanie import Document
class User(Document):
    name: str
    age: int
await User(name="Alice", age=30).insert()
await User.find(User.age >= 18).to_list()

# Mongose vs raw driver:
# ODMs add schemas, validation, and middleware
# but add overhead and a learning curve
# use the raw driver for max performance/control
17

GridFS와 대용량 파일

GridFS 기본

GridFS는 16MB BSON 문서 한도를 넘는 파일을 청크(기본 255KB)로 나눠 fs.chunks에 저장하고 메타데이터는 fs.files에 둡니다. 사실상 MongoDB 위의 파일시스템입니다. 16MB를 넘는 파일이면서 MongoDB의 복제와 샤딩 혜택이 필요할 때 사용하세요. 진짜 큰 미디어에는 S3나 CDN을 고려하세요.

mongodb
# GridFS stores files larger than 16MB (the BSON doc limit)
# by splitting them into chunks

# store a file via mongofiles (CLI)
mongofiles --db=mydb put large_video.mp4
mongofiles --db=mydb list
mongofiles --db=myfs get large_video.mp4

# two collections are used:
#   fs.files  - file metadata (one doc per file)
#   fs.chunks - file data in 255KB chunks

# query file metadata
db.fs.files.find().pretty()
db.fs.files.findOne({ filename: "large_video.mp4" })

# query chunks for a file
db.fs.chunks.find({ files_id: fileId }).sort({ n: 1 })

드라이버에서의 GridFS

드라이버는 GridFS를 스트리밍 API(GridFSBucket)로 노출합니다. 전체를 메모리에 올리지 않으므로 큰 파일에 이상적입니다. 업로드/다운로드는 파일이나 HTTP 응답에 파이프하는 스트림입니다. 업로드의 metadata는 어떤 문서 필드처럼 조회 가능합니다. GridFS 청크는 다운로드 시 자동 재조립됩니다. 버킷 이름(기본 'fs')은 설정 가능합니다.

mongodb
// Node.js: upload and download with streams
const { MongoClient, GridFSBucket } = require("mongodb")
const fs = require("fs")

const bucket = new GridFSBucket(db)

// upload a file
fs.createReadStream("video.mp4")
  .pipe(bucket.openUploadStream("video.mp4", {
    metadata: { uploadedBy: "alice" }
  }))

// download a file
bucket.openDownloadStreamByName("video.mp4")
  .pipe(fs.createWriteStream("downloaded.mp4"))

// delete a file
await bucket.delete(fileId)

// find files
const files = await bucket.find({}).toArray()

Time Series 컬렉션

time series 컬렉션(5.0+)은 시간 순서 데이터(IoT 센서, 지표, 로그)에 최적화되어 있습니다. 내부적으로 컬럼과 유사한 형식으로 저장해 일반 컬렉션보다 30~50% 압축과 더 빠른 범위 쿼리를 달성합니다. granularity는 데이터 간격에 맞추세요. TTL(expireAfterSeconds)이 오래된 데이터를 자동 삭제합니다. 시간 버킷 집계에는 $dateTrunc을 쓰세요.

mongodb
# create a time series collection (MongoDB 5.0+)
db.createCollection("temperatures", {
  timeseries: {
    timeField: "timestamp",
    metaField: "sensorId",
    granularity: "seconds"   // seconds|minutes|hours
  },
  expireAfterSeconds: 2592000   // auto-delete after 30 days
})

# insert measurements
db.temperatures.insertMany([
  { timestamp: ISODate(), sensorId: "s1", value: 22.5 },
  { timestamp: ISODate(), sensorId: "s1", value: 22.7 }
])

# query by time range
db.temperatures.find({
  sensorId: "s1",
  timestamp: { $gte: ISODate("2025-01-01") }
})

# aggregate averages per hour
db.temperatures.aggregate([
  { $group: {
    _id: { $dateTrunc: { date: "$timestamp", unit: "hour" } },
    avg: { $avg: "$value" }
  }}
])

Capped 컬렉션

capped 컬렉션은 삽입 순서를 유지하고 가득 차면 가장 오래된 문서를 덮어씁니다. 로그, 최근 활동 피드, 링 버퍼에 완벽합니다. 높은 처리량의 삽입과 tailable 커서(tail -f처럼)를 지원합니다. 한계: 개별 문서 삭제가 불가능하고 문서를 원래 크기보다 키울 수 없습니다. 실시간 테일링의 현대적 대안은 change stream입니다.

mongodb
# capped collections have a fixed size and overwrite old docs
db.createCollection("logs", {
  capped: true,
  size: 5242880,    # 5MB max
  max: 10000        # optional: max document count
})

# inserts only (no arbitrary deletes/updates)
db.logs.insertOne({ msg: "started", t: new Date() })

# high-throughput tail with a tailable cursor
const cursor = db.logs.find().addOption(2)  // tailable
while (true) {
  if (cursor.hasNext()) printjson(cursor.next())
}

# convert a regular collection to capped
db.runCommand({
  convertToCapped: "events",
  size: 1000000
})

BSON 크기와 문서 한도

16MB BSON 문서 한도는 하드 캡입니다. Object.bsonsize()로 문서 크기를 확인하세요. 큰 배열(수천 요소)은 문서를 부풀리고 갱신을 느리게 합니다(MongoDB는 갱신 시 문서 전체를 다시 씀). 무한 데이터(리뷰, 댓글, 로그 항목)는 참조를 둔 별도 컬렉션을 쓰세요. 16MB를 넘는 바이너리 블롭은 GridFS 또는 URL 참조를 둔 외부 저장소를 사용하세요.

mongodb
# maximum BSON document size: 16MB
# check a document's size (in bytes)
Object.bsonsize(db.users.findOne())

# large arrays/fields should be referenced, not embedded
# a product with 10000 reviews -> use a separate collection

# check if a document is too large
const doc = { /* ... huge doc ... */ }
const size = Object.bsonsize(doc)
if (size > 16 * 1024 * 1024) {
  throw new Error("Document exceeds 16MB BSON limit")
}

# GridFS bypasses the limit by chunking
# alternatively, store large blobs externally (S3)
# and keep only a URL reference in the document
18

SQL 비교와 마이그레이션

SQL-MongoDB 매핑

이 매핑이 SQL 개발자가 MongoDB를 배우는 가장 빠른 길입니다. 핵심 차이: MongoDB에는 고정 스키마가 없고(컬렉션의 문서가 달라질 수 있음), '조인'은 관련 데이터 내장 또는 $lookup으로 대체됩니다(SQL 조인보다 느리므로 스키마를 설계해 최소화하세요). SQL GROUP BY는 $group 집계 스테이지에 해당합니다.

mongodb
# SQL -> MongoDB terminology
# database          -> database
# table             -> collection
# row               -> document
# column            -> field
# index             -> index
# join              -> $lookup (or embed)
# primary key       -> _id (ObjectId by default)
# foreign key       -> reference (ObjectId field)
# group by          -> $group
# select            -> find / $project
# where             -> $match

# SQL query -> MongoDB query
# SELECT * FROM users WHERE age >= 18
db.users.find({ age: { $gte: 18 } })

# SELECT name, age FROM users
db.users.find({}, { name: 1, age: 1, _id: 0 })

# SELECT * FROM users ORDER BY age DESC LIMIT 10
db.users.find().sort({ age: -1 }).limit(10)

# SELECT city, COUNT(*) FROM users GROUP BY city
db.users.aggregate([
  { $group: { _id: "$city", count: { $sum: 1 } } }
])

SQL에서 마이그레이션

마이그레이션은 1:1 테이블-컬렉션 매핑이 아닙니다. MongoDB의 문서 모델에 맞게 스키마를 재설계해야 합니다. 작고 배타적이며 함께 접근되는 데이터는 내장하세요(사용자 프로필 + 주소). 크거나 공유되거나 무한한 데이터는 참조를 유지하세요(고객의 주문). MongoDB의 Relational Migrator 도구가 이 분석의 많은 부분을 자동화합니다. 그냥 옮기지 말고 스키마를 계획하세요.

mongodb
# step 1: export SQL data to JSON/CSV
# (mysqldump, pg_dump, or a script)

# step 2: transform relational data to documents
# SQL:
#   users(id, name, dept_id)
#   departments(id, name)
# MongoDB (embed small, related data):
db.users.insertOne({
  _id: 1,
  name: "Alice",
  department: { id: 10, name: "Engineering" }  # embedded
})

# step 3: for large related data, keep references
db.orders.insertOne({
  _id: 101,
  customerId: 1,    # reference, not embedded
  items: [...]      # embed order items (bounded)
})

# tools: MongoDB Relational Migrator (GUI), mongoimport
# https://www.mongodb.com/.../relational-migrator

트랜잭션 vs SQL ACID

MongoDB도 ACID를 제공합니다. 단일 문서 연산은 항상 원자적(트랜잭션 불필요)이고, 멀티 문서 트랜잭션(4.0+)은 컬렉션에 걸쳐 완전한 ACID를 제공합니다. 핵심 차이: SQL은 모든 문장에 ACID가 기본이지만, MongoDB는 관련 데이터를 한 문서에 두는(기본 원자적) 스키마 설계를 권하고 트랜잭션은 정말 필요할 때만 씁니다. 트랜잭션 오버헤드를 피하려 내장을 선호하세요.

mongodb
# SQL: ACID by default on every statement
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice';
UPDATE accounts SET balance = balance + 100 WHERE name = 'Bob';
COMMIT;

# MongoDB: single-document ops are atomic (ACID)
db.accounts.updateOne({name:"Alice"}, {$inc:{balance:-100}})
# (one document = one atomic operation)

# MongoDB: multi-document ACID (transactions, replica set)
const s = db.getMongo().startSession()
s.startTransaction()
db.accounts.updateOne({name:"Alice"},{$inc:{balance:-100}},{session:s})
db.accounts.updateOne({name:"Bob"},{$inc:{balance:100}},{session:s})
s.commitTransaction()

# prefer embedding to avoid transactions entirely
# (embedded data updates atomically in one document)

정규화 vs 비정규화

SQL은 중복 회피를 위해 정규화하고, MongoDB는 읽기 속도를 위해 비정규화합니다. 절충점: 비정규화된 데이터는 읽기 빠르지만 갱신이 어렵습니다(여러 문서). 거의 바뀌지 않는 데이터(국가명, 상품 카탈로그)는 비정규화하고 자주 바뀌는 데이터(가격, 재고)는 참조하세요. 올바른 균형은 읽기/쓰기 비율에 달려 있으니 모니터링하고 조정하세요.

mongodb
# SQL: normalize to avoid duplication (3NF)
#   users(id, name, city_id)
#   cities(id, name, country_id)
#   countries(id, name)
# -> 4 joins to get a user's country

# MongoDB: denormalize for read performance
db.users.insertOne({
  name: "Alice",
  city: "NYC",
  country: "USA"        # denormalized — duplicate but fast reads
})

# trade-off: updates must touch multiple documents
# when a city's name changes:
db.users.updateMany(
  { "city": "New York" },
  { $set: { "city": "NYC" } }
)

# rule: duplicate data that changes rarely,
# reference data that changes often

MongoDB vs SQL 선택

만능 '최고' 데이터베이스는 없습니다. MongoDB는 유연한 스키마, 계층 데이터, 수평 확장에 뛰어납니다. SQL은 관계 무결성, 복잡한 조인, 무거운 트랜잭션 워크로드에 뛰어납니다. 많은 현대 앱은 폴리글랏입니다. 카탈로그/콘텐츠/사용자 생성 데이터는 MongoDB, 금융 트랜잭션은 PostgreSQL. 유행이 아니라 워크로드에 맞춰 데이터베이스를 고르세요.

mongodb
# CHOOSE MongoDB when:
# - schema is flexible or evolving rapidly
# - data is naturally hierarchical (embed)
# - you need horizontal scaling (sharding)
# - reads >> writes and you can denormalize
# - document-oriented domain (CMS, product catalogs, IoT)

# CHOOSE SQL (PostgreSQL/MySQL) when:
# - schema is fixed and relational (banking, ERP)
# - you need complex multi-table joins frequently
# - transactions span many tables constantly
# - strong consistency is non-negotiable
# - your team knows SQL well

# HYBRID: use both — MongoDB for product catalog/comments,
# SQL for orders/payments. Many large apps are polyglot.

# AVOID MongoDB for:
# - heavy multi-entity transactional workloads
# - apps requiring complex cross-table joins as core feature
19

고급 집계

$merge와 $out (머터리얼라이즈드 뷰)

$out은 대상 컬렉션을 파이프라인 출력으로 교체합니다(파괴적). $merge는 더 유연해 기존 문서와 삽입, 교체, 결합이 가능하고 점진적 머터리얼라이즈드 뷰를 가능하게 합니다. 예약 갱신에는 $merge가 권장됩니다. 새/변경된 데이터만 갱신됩니다. 머터리얼라이즈드 뷰는 비싼 집계를 미리 계산해 대시보드 쿼리를 빠르게 합니다.

mongodb
# $out: write aggregation results to a NEW collection
db.orders.aggregate([
  { $group: { _id: "$customerId", total: { $sum: "$amount" } } },
  { $out: "customer_totals" }
])

# $merge: merge results into an EXISTING collection (flexible)
db.orders.aggregate([
  { $group: { _id: "$customerId", total: { $sum: "$amount" } } },
  { $merge: {
    into: "customer_totals",
    on: "_id",
    whenMatched: "replace",    // replace|keepExisting|merge|fail
    whenNotMatched: "insert"   // insert|discard|fail
  }}
])

# build a materialized view refreshed on a schedule
# (cron job or change-stream triggered)
db.daily_stats.aggregate([
  { $match: { date: today } },
  { $group: { _id: "$category", count: { $sum: 1 } } },
  { $merge: { into: "daily_stats", whenMatched: "replace" } }
])

윈도우 함수 ($setWindowFields)

$setWindowFields(5.0+)가 SQL 윈도우 함수를 MongoDB에 가져옵니다. 누계, 순위, 이동 평균, lag/lead. partitionBy가 PARTITION BY, sortBy가 ORDER BY, window가 프레임을 정의합니다. range 윈도우는 값 기준(예: 지난 7일)이고 documents 윈도우는 행 수 기준입니다. 시계열 분석과 보고에 필수입니다.

mongodb
# $setWindowFields: window functions (MongoDB 5.0+)
# like SQL OVER() — compute values across a window of docs
db.sales.aggregate([{
  $setWindowFields: {
    partitionBy: "$region",       # like PARTITION BY
    sortBy: { date: 1 },          # like ORDER BY
    output: {
      runningTotal: { $sum: "$amount", window: { documents: ["unbounded", "current"] } },
      rank: { $rank: {} },
      denseRank: { $denseRank: {} },
      movingAvg: { $avg: "$amount", window: { range: [-7, "current"], unit: "day" } },
      lagValue: { $shift: { by: -1, output: "$amount" } }
    }
  }
}])

# window: documents (count-based) or range (value-based)
# ["unbounded", "current"] = from start to current row
# [-3, "current"] = last 3 docs including current

$map, $filter, $reduce

$map, $filter, $reduce는 문서 내 변환을 위한 함수형 배열 연산자입니다. $map은 각 요소를 변환하고, $filter는 매칭 요소를 남기고, $reduce는 배열을 하나의 값으로 집계합니다. 'as' 변수(기본 $$this)가 현재 요소의 이름입니다. 많은 배열 연산에서 $unwind를 피하게 해 더 빠르고 깔끔합니다.

mongodb
# $map: transform each array element
{ $project: {
  squares: { $map: {
    input: "$nums",
    as: "n",
    in: { $multiply: ["$$n", "$$n"] }
  }}
}}

# $filter: keep elements matching a condition
{ $project: {
  adults: { $filter: {
    input: "$users",
    as: "u",
    cond: { $gte: ["$$u.age", 18] }
  }}
}}

# $reduce: fold an array into a single value
{ $project: {
  total: { $reduce: {
    input: "$items",
    initialValue: 0,
    in: { $add: ["$$value", "$$this.price"] }
  }}
}}

# variables: $$value (accumulator), $$this (current element), $$n (named)

$facet과 멀티 파이프라인

$facet은 한 쿼리에서 같은 입력에 여러 하위 파이프라인을 실행합니다. 분해, 통계, top N 등 데이터의 여러 뷰가 필요한 대시보드에 완벽합니다. 각 하위 파이프라인은 독립적이며 결과는 하위 파이프라인마다 필드를 갖는 하나의 문서입니다. 여러 왕복을 대체하고 일관된 스냅샷을 보장합니다.

mongodb
# run several aggregations on the same data in one pass
db.products.aggregate([{
  $facet: {
    "byCategory": [
      { $group: { _id: "$category", count: { $sum: 1 } } },
      { $sort: { count: -1 } }
    ],
    "priceStats": [
      { $group: { _id: null, avg: { $avg: "$price" }, max: { $max: "$price" } } }
    ],
    "topRated": [
      { $sort: { rating: -1 } },
      { $limit: 5 },
      { $project: { name: 1, rating: 1, _id: 0 } }
    ],
    "totalCount": [{ $count: "n" }]
  }
}])
# result: a single doc with all four arrays/objects

$bucket과 $bucketAuto

$bucket은 문서를 명시적 값 범위로 분류합니다(SQL의 CASE WHEN 같은). 가격 등급, 연령대, 히스토그램에 좋습니다. $bucketAuto는 MongoDB가 경계를 계산해 목표 버킷 수를 만들게 합니다(분포를 모를 때 데이터 탐색에 좋음). 경계는 왼쪽 포함, 오른쪽 제외입니다.

mongodb
# $bucket: group documents into explicit ranges
db.products.aggregate([{
  $bucket: {
    groupBy: "$price",
    boundaries: [0, 50, 100, 500, 1000],
    default: "other",
    output: {
      count: { $sum: 1 },
      names: { $push: "$name" },
      avgPrice: { $avg: "$price" }
    }
  }
}])
# buckets: [0,50), [50,100), [100,500), [500,1000), other

# $bucketAuto: let MongoDB choose the boundaries
db.products.aggregate([{
  $bucketAuto: {
    groupBy: "$price",
    buckets: 5,           # target 5 buckets
    output: { count: { $sum: 1 }, avg: { $avg: "$price" } }
  }
}])
# good for histograms and data exploration
20

모니터링과 문제 해결

모니터링할 핵심 지표

MongoDB의 네 가지 황금 신호: connections(한도 근접은 누수 또는 풀링 누락 신호), cache hit ratio(디스크에서 페이지 읽기는 RAM 압박 표시), replication lag(뒤처진 세컨더리는 장애 조치 시 데이터 유실 위험), queue depth(락 경쟁). 네 가지 모두 알림을 설정하세요. 떨어지는 캐시 히트율이 1위 성능 경고 신호입니다.

mongodb
# connections (watch for connection leaks)
db.serverStatus().connections
# { current, available, totalCreated }

# operation rates (queries/inserts/updates/deletes per sec)
db.serverStatus().opcounters

# WiredTiger cache (disk reads = cache misses)
db.serverStatus().wiredTiger.cache
# "bytes currently in the cache" vs "maximum bytes configured"
# "pages read into cache" should be low (cache hits)

# replication lag (critical for HA)
rs.printSecondaryReplicationInfo()

# queue depth (operations waiting for locks)
db.serverStatus().globalLock.currentQueue

# open cursors (watch for leaks)
db.serverStatus().metrics.cursor

락 경쟁 해소

MongoDB는 문서 수준 잠금(WiredTiger)을 쓰므로 경쟁은 드뭅니다. 하지만 인덱스 없는 쿼리, 거대한 정렬, 긴 트랜잭션은 여전히 막습니다. currentOp가 범인을 찾고 killOp가 멈춥니다. 근본 원인은 보통 누락된 인덱스입니다(explain 실행). 큰 컬렉션의 스키마 마이그레이션은 오래 잠글 수 있으므로 작은 배치로 또는 트래픽 적을 때 수행하세요.

mongodb
# check current queue (operations waiting)
db.serverStatus().globalLock.currentQueue
# { readers, writers, total }

# find long-running operations
db.currentOp({
  secs_running: { $gte: 5 },
  op: { $ne: "none" }
})

# kill a long-running op blocking others
db.killOp(opid)

# common causes of lock contention:
# - unindexed queries (COLLSCAN holds locks)
# - large in-memory sorts
# - long transactions
# - schema migrations on large collections

# check for slow ops in the log
db.adminCommand({ getLog: "global" }).log
  .filter(l => l.includes(" Slow query"))

메모리와 디스크 분석

WiredTiger의 캐시가 메모리 최전선입니다. 더티 페이지로 가득하면 쓰기가 느려집니다(디스크 플러시). 'pages read into cache'가 높으면 RAM 또는 스캔을 줄일 인덱스를 추가하세요. 쓰지 않는 인덱스는 버리세요. 디스크와 메모리를 소비하고 쓰기를 느리게 합니다. 저장 성장을 모니터링해 용량 요구를 예측하세요. 샤딩 클러스터에서 점보 청크(이동 불가능할 만큼 큼)는 나쁜 샤드 키의 표시입니다.

mongodb
# check storage engine memory usage
db.serverStatus().wiredTiger.cache
# "maximum bytes configured" = cache limit (default 50% RAM)
# "tracked dirty bytes" = dirty pages awaiting flush
# target: dirty < 20%, cache usage < 95%

# disk space per collection
db.users.stats().storageSize
db.users.totalIndexSize()

# find the largest collections
db.getCollectionNames().map(c => ({
  name: c, size: db.getCollection(c).storageSize()
})).sort((a,b) => b.size - a.size).slice(0, 5)

# check for jumbo chunks (sharded clusters)
sh.status(true)

# review index sizes (drop unused indexes)
db.users.getIndexes().map(i => ({
  name: i.name, size: db.users.stats().indexSizes[i.name]
}))

로그 분석

mongod 로그는 느린 연산, 선거, 오류 등을 기록합니다. slowOpThresholdMs를 SLO 위 쿼리를 잡도록 설정하세요. getLog는 메모리 내 링 버퍼를 가져오고, 디스크 로그는 재시작에도 유지됩니다. logRotate는 현재 로그를 아카이브합니다(매일 로테이션에는 logrotate와 함께). 심층 디버깅을 위해 일시적으로 구성 요소 verbosity를 올리세요(예: 선거 문제는 replication: 2), 그다음 되돌리세요.

mongodb
# view recent log entries
db.adminCommand({ getLog: "global" })

# log slow queries (set threshold)
db.adminCommand({
  setParameter: 1,
  logComponentVerbosity: { query: { verbosity: 1 } }
})

# mongod.conf: log slow operations
# operationProfiling:
#   mode: slowOp
#   slowOpThresholdMs: 100
#   slowOpSampleRate: 1.0

# grep the mongod log for slow queries
grep "Slow query" /var/log/mongodb/mongod.log
grep "COMMAND" /var/log/mongodb/mongod.log | tail -50

# rotate logs
db.adminCommand({ logRotate: 1 })

# set log verbosity for a component
db.adminCommand({
  setParameter: 1,
  logComponentVerbosity: { replication: 2 }
})

흔한 오류와 해법

가장 흔한 MongoDB 오류들입니다. 중복 키 오류는 _id 또는 유니크 인덱스 위반에서 오며 앱 코드에서 처리하세요. 집계 메모리 한도는 allowDiskUse로 해결합니다(느리지만 동작). 트랜잭션의 WriteConflict는 경쟁 상황에서 정상이므로 재시도하세요. 커서 타임아웃은 배치 처리가 너무 느리다는 뜻이므로 더 작은 배치 또는 noCursorTimeout을 쓰세요(단, 항상 커서를 닫으세요).

mongodb
# ERROR: "E11000 duplicate key"
# cause: _id or unique index conflict
# fix: check the duplicate value, use upsert, or catch the error

# ERROR: "QueryExceededMemoryLimitNoDiskUseAllowed"
# cause: aggregation stage exceeded 100MB RAM
# fix: add { allowDiskUse: true } or add $match early
db.big.aggregate([...], { allowDiskUse: true })

# ERROR: "BSONObjTooLarge"
# cause: document > 16MB
# fix: use GridFS or split the document

# ERROR: "WriteConflict" (transaction)
# cause: two transactions modified the same doc
# fix: retry the transaction (TransientTransactionError)

# ERROR: "ReplicaSetNoPrimary"
# cause: no primary (election in progress)
# fix: wait for election; check rs.status()

# ERROR: "cursor not found"
# cause: cursor timed out (10 min default)
# fix: use noCursorTimeout or process faster

Was this helpful?