A · Queries and changes
CRUD: shape a query around the document
AMongoDB CRUD methods operate on documents in a collection. A filter describes which records qualify. Comparison operators such as $gte and $in belong inside a field condition; logical operators such as $or combine conditions.
db.orders.find(
{ status: "paid", total: { $gte: 100 } },
{ customer: 1, total: 1 }
).sort({ total: -1 })Read the pieces
- The filter selects paid orders with a total of at least 100.
- The projection includes requested fields; MongoDB includes
_id unless you explicitly exclude it. - The sort uses descending order. Add a stable tie-breaker when page order must remain deterministic.
Common confusion: updateOne() changes one matching document; updateMany() changes every match. Operators such as $set update selected fields, while a replacement document has different semantics.
A · 조회와 변경
CRUD: 문서에 맞춰 쿼리 구성하기
AMongoDB CRUD 메서드는 컬렉션의 문서를 조회하고 변경합니다. 필터는 대상 문서를 설명합니다. $gte, $in 같은 비교 연산자는 필드 조건에 넣고, $or 같은 논리 연산자로 조건을 묶습니다.
db.orders.find(
{ status: "paid", total: { $gte: 100 } },
{ customer: 1, total: 1 }
).sort({ total: -1 })각 부분 읽기
- 필터는 결제 완료 상태이면서 총액이 100 이상인 주문을 고릅니다.
- 프로젝션은 요청한 필드를 포함합니다. 명시적으로 제외하지 않으면
_id는 기본 포함됩니다. - 정렬에서 음수는 내림차순입니다. 페이지 순서를 안정적으로 유지하려면 동률을 구분할 필드를 추가하세요.
자주 헷갈리는 점: updateOne()은 문서 하나, updateMany()는 모든 일치 문서를 변경합니다. $set 같은 업데이트 연산자와 새 문서로 교체하는 작업은 의미가 다릅니다.
Worked case: expire unpaid orders safely
Cancel orders still pending after their payment deadline. Including the current state in the filter makes a retry skip orders paid in the meantime.
db.orders.updateMany(
{ status: "pending", paymentDueAt: { $lt: now } },
{ $set: { status: "cancelled", cancelledAt: now } }
)Why the tempting answer fails: Replacing with { status: "cancelled" } can discard other fields; updateOne() leaves other expired orders unchanged.
In production: preview with countDocuments(), make the transition safe to retry, and inspect matchedCount. Multi-document updates are atomic per document; use a transaction only if the whole group must succeed together.
실전 사례: 미결제 주문을 안전하게 만료시키기
결제 기한이 지난 주문을 취소할 때 현재 상태도 필터에 포함하면, 재시도 사이에 결제된 주문은 건너뜁니다.
db.orders.updateMany(
{ status: "pending", paymentDueAt: { $lt: now } },
{ $set: { status: "cancelled", cancelledAt: now } }
)그럴듯한 오답이 틀리는 이유: { status: "cancelled" }로 교체하면 다른 필드를 잃을 수 있고, updateOne()은 나머지 만료 주문을 바꾸지 않습니다.
실무에서 확인할 점: countDocuments()로 먼저 대상을 미리 보고, 재시도에 안전한 상태 전이를 만든 뒤 matchedCount를 확인하세요. 여러 문서 수정은 문서별 원자성이므로 전체 성공이 함께 보장돼야 할 때 트랜잭션을 고려합니다.
B · Application code
Node.js driver: manage a client and its work
BA MongoClient represents a connection pool and is commonly reused across requests. Create it during startup, connect once, and close it when the process shuts down. Driver calls are asynchronous; await the operation whose result you need.
const client = new MongoClient(uri);
await client.connect();
try {
const orders = client.db("shop").collection("orders");
const order = await orders.findOne({ _id: orderId });
} finally {
await client.close();
}Remember
find() returns a cursor, not an array. Use toArray() for a bounded result set, or iterate when results may be large.- Await writes when later work depends on completion or result counts.
- Sessions provide transaction context. Every operation in a transaction must use the same session.
Common confusion: opening a new client for every request throws away pooling and increases connection churn. Reuse the client and define its lifecycle.
B · 애플리케이션 코드
Node.js 드라이버: 클라이언트와 작업 관리
BMongoClient는 연결 풀을 나타내며 여러 요청에서 재사용합니다. 애플리케이션 시작 시 만들고 연결한 뒤 종료 시 닫습니다. 드라이버 메서드는 비동기로 동작하므로 결과가 필요한 호출을 await 하세요.
const client = new MongoClient(uri);
await client.connect();
try {
const orders = client.db("shop").collection("orders");
const order = await orders.findOne({ _id: orderId });
} finally {
await client.close();
}기억할 점
find()는 배열이 아니라 커서를 반환합니다. 결과가 작으면 toArray()를, 클 수 있으면 커서 반복을 사용하세요.- 후속 작업이 쓰기 완료나 결과 건수에 의존하면 쓰기 작업을
await 하세요. - 세션은 트랜잭션 컨텍스트를 제공합니다. 트랜잭션 안의 모든 작업에 같은 세션을 전달해야 합니다.
자주 헷갈리는 점: 요청마다 클라이언트를 새로 만들면 연결 풀을 활용하지 못합니다. 클라이언트를 재사용하고 종료 시점을 정하세요.
Worked case: return one page without loading everything
An endpoint needs 25 recent orders. find() creates a cursor; consuming it retrieves documents.
const cursor = orders.find({ customerId }, {
projection: { total: 1, placedAt: 1 },
sort: { placedAt: -1, _id: -1 }, limit: 25
});
for await (const order of cursor) send(order);Why the tempting answer fails: await orders.find(...) does not turn a cursor into an array. An unbounded toArray() can use far more application memory than intended.
In production: reuse one MongoClient per process so requests share connection pools. Bound user-facing reads and close the client during graceful shutdown.
실전 사례: 전부 읽지 않고 결과 한 페이지 반환하기
API에서 최근 주문 25개만 가져온다고 해봅시다. find()는 커서를 만들며, 커서를 소비할 때 문서를 읽습니다.
const cursor = orders.find({ customerId }, {
projection: { total: 1, placedAt: 1 },
sort: { placedAt: -1, _id: -1 }, limit: 25
});
for await (const order of cursor) send(order);그럴듯한 오답이 틀리는 이유: await orders.find(...)를 써도 커서는 배열이 되지 않습니다. 제한 없는 toArray()는 앱 메모리를 예상보다 많이 쓸 수 있습니다.
실무에서 확인할 점: 프로세스마다 MongoClient 하나를 재사용해 요청들이 연결 풀을 공유하게 하세요. 사용자 조회에는 건수 제한을 두고 정상 종료 시 클라이언트를 닫습니다.
C · Query performance
Indexes: trade write cost for faster reads
CAn index stores an ordered representation of selected field values so MongoDB can find documents without scanning the whole collection. Indexes improve supported reads, but inserts and updates also maintain them.
db.orders.createIndex({ status: 1, createdAt: -1 })
db.orders.find({ status: "paid" }).sort({ createdAt: -1 })Compound index order matters
A compound index can support queries using its leading fields. Equality, sort, and range fields often guide field order, but selectivity and query shape matter; verify the real plan with explain().
- A unique index enforces uniqueness for indexed keys.
- A multikey index is created when an indexed field contains an array.
- A TTL index removes eligible documents after a configured time; it is not an exact real-time timer.
Common confusion: adding more indexes is not free. Check query plans and write volume, and remove indexes that do not serve a real access pattern.
C · 쿼리 성능
인덱스: 빠른 조회와 쓰기 비용의 균형
C인덱스는 선택한 필드 값을 정렬해 전체 컬렉션을 훑지 않고 문서를 찾도록 돕습니다. 읽기는 빨라질 수 있지만 삽입과 수정 시 인덱스도 관리해야 합니다.
db.orders.createIndex({ status: 1, createdAt: -1 })
db.orders.find({ status: "paid" }).sort({ createdAt: -1 })복합 인덱스의 필드 순서
복합 인덱스는 앞쪽 필드를 사용하는 쿼리를 지원할 수 있습니다. 동등 조건, 정렬, 범위 필드의 순서를 고려하되 데이터 선택도와 쿼리 형태를 함께 봐야 합니다. explain()으로 계획을 확인하세요.
- 고유 인덱스는 인덱스 키의 중복을 막습니다.
- 인덱스 대상 필드가 배열이면 다중 키 인덱스가 만들어집니다.
- TTL 인덱스는 시간이 지난 문서를 제거하지만 정확한 실시간 타이머는 아닙니다.
자주 헷갈리는 점: 인덱스 추가에는 비용이 듭니다. 쿼리 계획과 쓰기량을 살피고 사용되지 않는 인덱스는 정리하세요.
Worked case: support a filter and sort together
A dashboard lists the newest paid orders. Test an index whose leading field matches the equality filter and whose next field supports the sort.
db.orders.createIndex({ status: 1, createdAt: -1 })
db.orders.find({ status: "paid" })
.sort({ createdAt: -1 }).limit(20)
.explain("executionStats")Why the tempting answer fails: An index led by an unrelated field may not narrow this query well. Even a plausible index is not guaranteed to be selected by the query planner.
In production: compare nReturned, totalKeysExamined, and totalDocsExamined with realistic data. Indexes use storage and add work to writes, so keep ones that serve measured access patterns.
실전 사례: 필터와 정렬을 함께 지원하기
대시보드에 결제 완료 주문을 최신순으로 보여준다면, 동등 조건 필드를 앞에 두고 다음 필드가 정렬을 지원하도록 인덱스를 검증해 볼 수 있습니다.
db.orders.createIndex({ status: 1, createdAt: -1 })
db.orders.find({ status: "paid" })
.sort({ createdAt: -1 }).limit(20)
.explain("executionStats")그럴듯한 오답이 틀리는 이유: 관련 없는 필드가 앞선 인덱스는 이 조회 범위를 잘 좁히지 못할 수 있습니다. 구성이 맞아 보여도 쿼리 플래너가 반드시 그 인덱스를 선택하지는 않습니다.
실무에서 확인할 점: 현실적인 데이터로 nReturned, totalKeysExamined, totalDocsExamined를 비교하세요. 인덱스는 저장 공간과 쓰기 비용이 드니 측정된 조회 패턴에 필요한 것을 유지합니다.
D · Database foundations
MongoDB overview: documents and deployment
DMongoDB stores BSON documents in collections. BSON is a binary serialization with additional types, including dates and 64-bit integers. A database groups collections; a collection can hold documents whose fields evolve over time.
{
_id: ObjectId("..."),
customer: { id: 42, name: "Mina" },
placedAt: ISODate("2026-10-01T09:00:00Z"),
total: Decimal128("128.50")
}Availability and scale
- A replica set maintains copies of data and elects a primary for writes. Replication supports availability and redundancy.
- Sharding distributes data across shards to scale storage and throughput. A shard key determines document distribution.
- Atlas is MongoDB's managed cloud service; self-managed deployments give operators more infrastructure responsibility.
Common confusion: replication and sharding solve different problems. Replication copies data for availability; sharding partitions data for distribution and scale.
D · 데이터베이스 기초
MongoDB 개요: 문서와 배포 방식
DMongoDB는 BSON 문서를 컬렉션에 저장합니다. BSON은 날짜와 64비트 정수처럼 JSON보다 다양한 타입을 지원하는 바이너리 형식입니다. 데이터베이스는 컬렉션을 묶고, 문서는 시간에 따라 다른 필드 구성을 가질 수 있습니다.
{
_id: ObjectId("..."),
customer: { id: 42, name: "Mina" },
placedAt: ISODate("2026-10-01T09:00:00Z"),
total: Decimal128("128.50")
}가용성과 확장
- 복제 세트는 데이터 사본을 유지하고 쓰기 작업을 위한 프라이머리를 선출합니다. 복제는 가용성과 중복성을 돕습니다.
- 샤딩은 샤드 키를 기준으로 데이터를 나눠 저장 공간과 처리량을 확장합니다.
- Atlas는 MongoDB 관리형 클라우드 서비스이며, 자체 관리 배포는 운영자가 인프라를 더 많이 책임집니다.
자주 헷갈리는 점: 복제와 샤딩의 목적은 다릅니다. 복제는 가용성을 위해 데이터를 복사하고, 샤딩은 분산과 확장을 위해 데이터를 나눕니다.
Worked case: separate failover from distribution
A service first needs to survive a host failure, then spread a growing workload across machines. Replica sets keep copies and elect a primary; sharding distributes data according to a shard key. Shards commonly use replica sets too.
Replica set → copies + primary election
Sharding → partitions + shard key
Atlas → managed deployment option
Why the tempting answer fails: Replication alone does not partition data to add shard capacity. Sharding is not the same as redundant copies, and neither replaces a backup.
In production: choose a shard key from query and growth patterns. Accidental deletes are replicated too, so plan backup and recovery separately.
실전 사례: 장애 조치와 데이터 분산 구분하기
호스트 장애에도 서비스를 유지하고, 커지는 작업량을 여러 머신에 나눠야 한다고 해봅시다. 복제 세트는 사본과 프라이머리 선출을 제공하고, 샤딩은 샤드 키에 따라 데이터를 분산합니다. 샤드도 보통 복제 세트로 운영합니다.
복제 세트 → 사본 + 프라이머리 선출
샤딩 → 데이터 분할 + 샤드 키
Atlas → 관리형 배포 선택지
그럴듯한 오답이 틀리는 이유: 복제만으로 데이터를 분할해 샤드 용량을 늘릴 수 없습니다. 샤딩은 데이터 사본을 유지하는 것과 다르며 둘 다 백업을 대신하지 않습니다.
실무에서 확인할 점: 실제 쿼리와 데이터 증가 양상에 맞춰 샤드 키를 고르세요. 실수로 삭제한 데이터도 복제되므로 백업과 복구는 별도로 설계해야 합니다.
E · Application data
Data modeling: design for access patterns
EStart with the questions the application asks and how often it asks them. Embedding related data can make a common read a single-document operation. Referencing can reduce duplication or keep a growing relationship in a separate collection.
{
_id: 9001,
customerId: 42,
items: [{ sku: "book-1", quantity: 2, unitPrice: 18 }]
}Choose with growth in mind
- Embed when child data is bounded, belongs to the parent, and is commonly read together.
- Reference when records grow without a practical bound, are shared by many parents, or are read independently.
- Denormalize selectively when faster reads justify keeping duplicated values in sync.
- Schema validation can enforce expected shapes while an application evolves deliberately.
Common confusion: document databases still need deliberate schemas. Flexible storage does not decide which fields belong together or how updates stay consistent.
E · 애플리케이션 데이터
데이터 모델링: 조회 패턴에 맞춰 설계
E먼저 애플리케이션이 어떤 데이터를 얼마나 자주 조회하는지 정리하세요. 함께 조회하는 관련 데이터를 내장하면 한 문서 조회로 끝낼 수 있습니다. 참조는 중복을 줄이거나 계속 커지는 관계를 별도 컬렉션에 둘 때 유용합니다.
{
_id: 9001,
customerId: 42,
items: [{ sku: "book-1", quantity: 2, unitPrice: 18 }]
}데이터 증가도 고려하기
- 하위 데이터의 크기가 제한적이고 부모에 속하며 함께 자주 조회되면 내장을 고려합니다.
- 관계가 계속 커지거나 여러 부모가 공유하거나 별도로 조회되면 참조가 유용합니다.
- 읽기 속도가 중요하면 값을 복제할 수 있지만 동기화 책임이 생깁니다.
- 스키마 검증으로 애플리케이션이 바뀌는 동안 기대하는 문서 형태를 확인할 수 있습니다.
자주 헷갈리는 점: 문서 데이터베이스도 의도적인 스키마 설계가 필요합니다. 유연한 저장 방식이 필드 관계와 일관성 문제를 대신 결정해 주지는 않습니다.
Worked case: preserve the price paid on an order
An order page needs its line items and checkout price. Embed a bounded snapshot in the order; keep the shared product catalog as the source of current details.
{
_id: 9001, customerId: 42,
items: [{ sku: "book-1", title: "MongoDB Basics",
quantity: 2, unitPriceAtPurchase: 18 }]
}Why the tempting answer fails: Looking up only the current catalog price can change how an old receipt appears. Embedding every order ever made in a customer document creates an unbounded array.
In production: snapshot values that must remain historically true, and reference canonical records for current details. Decide which copy is authoritative for each field.
실전 사례: 주문 당시 가격 보존하기
주문 화면에는 항목과 결제 당시 가격이 필요합니다. 크기가 제한된 스냅샷은 주문에 내장하고, 현재 상품 정보의 원본은 공유 카탈로그에 둡니다.
{
_id: 9001, customerId: 42,
items: [{ sku: "book-1", title: "MongoDB Basics",
quantity: 2, unitPriceAtPurchase: 18 }]
}그럴듯한 오답이 틀리는 이유: 현재 카탈로그 가격만 조회하면 과거 영수증의 가격도 바뀌어 보일 수 있습니다. 고객 문서 안에 모든 주문을 계속 내장하면 끝없이 커지는 배열이 됩니다.
실무에서 확인할 점: 과거에도 유지되어야 할 값은 스냅샷으로 저장하고, 최신 정보는 기준 문서를 참조하세요. 각 필드의 원본이 어느 쪽인지 정해야 합니다.
F · Developer workflow
Tools: pick the right view for the task
FMongoDB tools cover different parts of a development workflow. mongosh runs commands interactively, Compass provides a visual way to explore data, and Atlas UI manages cloud resources.
- Use
mongosh to test a query or inspect server information with commands. - Use Compass to browse documents, build filters, and inspect indexes visually.
- Use Atlas UI for managed deployments, database access controls, monitoring, and cluster configuration.
- Use application drivers for repeatable production operations; manual console work is not an application integration strategy.
Study prompt: Compare a visual workflow with a scriptable one. The right tool depends on repeatability, context, and who needs to operate it.
F · 개발자 작업 흐름
도구: 작업에 맞는 화면 선택하기
FMongoDB 도구는 개발 과정의 서로 다른 부분을 돕습니다. mongosh는 명령을 대화식으로 실행하고, Compass는 데이터를 시각적으로 살펴보며, Atlas UI는 클라우드 클러스터를 관리합니다.
mongosh로 쿼리를 시험하거나 명령으로 서버 정보를 확인합니다.- Compass에서 문서를 탐색하고 필터를 만들며 인덱스를 시각적으로 봅니다.
- Atlas UI에서 관리형 배포, 접근 권한, 모니터링, 클러스터 설정을 관리합니다.
- 반복 가능한 운영 작업은 애플리케이션 드라이버로 구현합니다. 콘솔의 수동 작업은 앱 연동을 대신하지 않습니다.
생각해 볼 문제: 시각적 방식과 스크립트 방식을 비교해 보세요. 반복 가능성, 작업 맥락, 운영 주체에 따라 알맞은 도구가 달라집니다.
Worked case: investigate a slow query, then ship a fix
Use mongosh or Compass to inspect a representative query and plan. Use a driver for repeatable application requests and Atlas UI to manage a hosted cluster and its access.
db.orders.find({ status: "paid" })
.sort({ createdAt: -1 }).limit(20)
.explain("executionStats")Why the tempting answer fails: Compass is a client, not the database server. Atlas is the managed service and a driver is the application interface; they have different jobs.
In production: verify plans against realistic data, then use the normal change process for an index. Give each operator only the database permissions the task needs.
실전 사례: 느린 쿼리를 분석하고 수정하기
실제와 비슷한 쿼리와 계획은 mongosh나 Compass로 확인합니다. 반복되는 앱 요청은 드라이버로 구현하고 호스팅 클러스터와 접근 권한은 Atlas UI에서 관리합니다.
db.orders.find({ status: "paid" })
.sort({ createdAt: -1 }).limit(20)
.explain("executionStats")그럴듯한 오답이 틀리는 이유: Compass는 DB 서버가 아니라 클라이언트입니다. Atlas는 관리형 서비스이고 드라이버는 앱 연결 방식으로 서로 역할이 다릅니다.
실무에서 확인할 점: 현실적인 데이터로 실행 계획을 확인하고 정해진 변경 절차로 인덱스를 반영하세요. 작업자에게 필요한 DB 권한만 부여합니다.