데이터베이스, 컬렉션, 네임스페이스
데이터베이스를 만들고 컬렉션을 추가하며 MongoDB가 네임스페이스 수준에서 데이터를 구성하는 방식을 이해합니다.
데이터베이스, 컬렉션, 네임스페이스은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
MongoDB's Three-Level Hierarchy
MongoDB nests data in three levels: Database, Collection, Document. It mirrors SQL's database, table, row — and one server can hold many of each.
What Is a Namespace?
A namespace names a collection by combining database and collection with a dot, like myapp.users. You'll see this notation in logs and explain output.
// Namespace: database.collection
// 'shop' database, 'products' collection:
use shop
db.products.find({})
// MongoDB internally refers to this as 'shop.products'
// You can also reference it explicitly:
db.getSiblingDB('shop').getCollection('products').find({})Switching and Creating Databases
In mongosh, use switches databases. There's no CREATE DATABASE — MongoDB makes one lazily, the moment you insert your first document. The code shows it.
// Switch to (or create) a database
use myNewApp
// 'myNewApp' doesn't exist yet - no error, but not visible in 'show dbs'
// Insert a document to materialize the database
db.users.insertOne({ name: 'Alice' });
// Now 'myNewApp' appears:
show dbs
// admin 0.000GB
// local 0.000GB
// myNewApp 0.000GBSystem Databases: admin, local, config
MongoDB keeps three system databases: admin for users and roles, local for replication data, and config for sharded-cluster metadata. Good to recognize, not to touch.
// View all databases on the server
show dbs
// admin 0.000GB
// config 0.000GB
// local 0.004GB
// shop 0.012GB
// myapp 0.008GB
// List databases programmatically
db.adminCommand({ listDatabases: 1 });Creating Collections Explicitly
Use createCollection when you need special options up front — capped, time-series, clustered, or a schema validator. The code creates one with validation rules.
// Create a collection with a JSON Schema validator
db.createCollection('products', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['name', 'price'],
properties: {
name: { bsonType: 'string' },
price: { bsonType: 'number', minimum: 0 }
}
}
}
});Listing and Inspecting Collections
A few commands let you explore your database: list collections, get detailed info, and check storage stats. show collections is the quick one. The code shows more.
use shop
show collections
// orders
// products
// users
db.getCollectionInfos();
// Returns array of {name, type, options, idIndex} per collection
db.orders.stats().count;
// 15234
db.orders.totalIndexSize();
// 2359296 (bytes)Renaming and Dropping Collections
You can rename a collection instantly, or drop one to delete it for good. Dropping is permanent — there's no recycle bin, so back up first in production.
// Rename a collection
db.oldUsers.renameCollection('users');
// { ok: 1 }
// Drop a collection - IRREVERSIBLE
db.tempData.drop();
// true
// Drop the entire database - EXTREMELY DANGEROUS
// db.dropDatabase();
// Use only in development or with full backupMulti-Tenancy With Databases
For SaaS apps, multi-tenancy can mean a database per customer for strong isolation, or one shared collection filtered by a tenantId field. The code shows both.
// Option 1: Database-per-tenant
const db = client.db('tenant_' + tenantId);
db.users.find({});
// Each tenant has completely isolated data
// Option 2: Shared collection with tenantId field
const db = client.db('saas_app');
db.users.find({ tenantId: tenantId });
// All tenants share one collection, filtered by tenantIdCollection Naming Best Practices
A few naming habits prevent headaches: stay consistent, use plural nouns like users, and avoid special characters. Good naming conventions make code easier to read.
// Good collection names
db.users.find({});
db.order_items.find({});
db.productCategories.find({});
// Avoid these
db['$sales'].find({}); // $ prefix causes issues
db['system.logs'].find({}); // reserved prefix
db['my.collection'].find({}); // dot in name causes confusionThe WiredTiger Storage Engine
MongoDB's default storage engine is WiredTiger. It allows many writes at once without blocking, compresses data on disk, and journals writes so crashes don't lose data.
// Check current storage engine
db.serverStatus().storageEngine;
// { name: 'wiredTiger', supportsCommittedReads: true, ... }
// Collection stats show compression savings
db.orders.stats();
// storageSize: 2097152 (compressed on disk)
// size: 8388608 (uncompressed logical size)Understanding the Oplog
The oplog is a special log of every write in a replica set. Secondaries replay it to stay in sync, and it also powers MongoDB's live Change Streams.
// Inspect oplog in mongosh (replica set members only)
use local
db.oplog.rs.find().sort({ $natural: -1 }).limit(3);
// { op: 'i', ns: 'shop.orders', o: { _id: ..., ... } }
// op: 'i'=insert, 'u'=update, 'd'=delete, 'c'=commandQuick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
You learned MongoDB organizes data as Database, Collection, Document, that databases are created lazily, and that WiredTiger powers storage. Next: the mongosh shell.
자주 묻는 질문
“데이터베이스, 컬렉션, 네임스페이스” 강의는 무료인가요?
네 — “데이터베이스, 컬렉션, 네임스페이스” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“데이터베이스, 컬렉션, 네임스페이스”에서 뭘 배우나요?
데이터베이스를 만들고 컬렉션을 추가하며 MongoDB가 네임스페이스 수준에서 데이터를 구성하는 방식을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“데이터베이스, 컬렉션, 네임스페이스” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- BSON 문서란 무엇인가요?
- 컬렉션과 SQL 테이블 비교
- 데이터베이스, 컬렉션, 네임스페이스
- mongosh 셸 핵심