MongoDB 개발 문서
목차
MongoDB 소개
MongoDB는 문서 지향(Document-Oriented) NoSQL 데이터베이스로, JSON과 유사한 BSON(Binary JSON) 형식으로 데이터를 저장합니다. 관계형 데이터베이스와 달리 스키마가 유연하며, 스케일링이 용이하고 대용량 데이터 처리에 적합합니다.
주요 특징
- 문서 기반 (Document-based)
- 스키마 없음 (Schema-less)
- 수평적 확장성 (Horizontal Scalability)
- 고성능 (High Performance)
- 고가용성 (High Availability)
- 지리 정보 인덱싱 (Geospatial Indexing)
- 집계 프레임워크 (Aggregation Framework)
설치 및 설정
MongoDB 설치
Ubuntu에 설치하기
# MongoDB 공개키 가져오기
wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -
# MongoDB 리포지토리 추가
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
# 패키지 업데이트
sudo apt-get update
# MongoDB 설치
sudo apt-get install -y mongodb-org
# MongoDB 서비스 시작
sudo systemctl start mongod
# 부팅 시 MongoDB 자동 시작 설정
sudo systemctl enable mongodmacOS에 설치하기
# Homebrew를 사용하여 설치
brew tap mongodb/brew
brew install mongodb-community
# MongoDB 서비스 시작
brew services start mongodb-communityWindows에 설치하기
- MongoDB 다운로드 센터에서 MSI 설치 파일을 다운로드합니다.
- 다운로드한 MSI 파일을 실행하고 설치 마법사의 안내를 따릅니다.
- "MongoDB를 서비스로 설치" 옵션을 선택하여 자동으로 시작되도록 설정합니다.
MongoDB Compass 설치
MongoDB Compass는 MongoDB를 위한 GUI 도구입니다. 다운로드 페이지에서 설치할 수 있습니다.
Node.js에서 MongoDB 연결 설정
const { MongoClient } = require('mongodb');
// 연결 문자열
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function connect() {
try {
// MongoDB에 연결
await client.connect();
console.log('MongoDB에 성공적으로 연결되었습니다');
// 데이터베이스 및 컬렉션 선택
const database = client.db('testdb');
const collection = database.collection('users');
return collection;
} catch (error) {
console.error('MongoDB 연결 오류:', error);
throw error;
}
}
module.exports = { connect, client };MongoDB Atlas 클라우드 서비스 사용하기
MongoDB Atlas는 MongoDB의 클라우드 서비스로, 다음 단계를 통해 설정할 수 있습니다:
- MongoDB Atlas 웹사이트에 가입합니다.
- 새 클러스터를 생성합니다.
- 네트워크 액세스 및 사용자 설정을 구성합니다.
- 연결 문자열을 얻습니다.
// Atlas 연결 예제
const uri = 'mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>?retryWrites=true&w=majority';
const client = new MongoClient(uri);기본 CRUD 작업
생성 (Create)
// 단일 문서 삽입
async function insertOneUser(collection, userData) {
try {
const result = await collection.insertOne(userData);
console.log(`문서 삽입 성공. ID: ${result.insertedId}`);
return result;
} catch (error) {
console.error('문서 삽입 오류:', error);
throw error;
}
}
// 여러 문서 삽입
async function insertManyUsers(collection, usersData) {
try {
const result = await collection.insertMany(usersData);
console.log(`${result.insertedCount}개의 문서가 삽입되었습니다`);
return result;
} catch (error) {
console.error('문서 삽입 오류:', error);
throw error;
}
}
// 사용 예제
const userData = {
name: '홍길동',
email: 'hong@example.com',
age: 30,
createdAt: new Date()
};
const usersData = [
{ name: '김철수', email: 'kim@example.com', age: 25 },
{ name: '이영희', email: 'lee@example.com', age: 28 }
];
// 함수 호출
insertOneUser(collection, userData);
insertManyUsers(collection, usersData);읽기 (Read)
// 단일 문서 조회
async function findOneUser(collection, query) {
try {
const result = await collection.findOne(query);
return result;
} catch (error) {
console.error('문서 조회 오류:', error);
throw error;
}
}
// 여러 문서 조회
async function findUsers(collection, query, options = {}) {
try {
const cursor = collection.find(query, options);
return await cursor.toArray();
} catch (error) {
console.error('문서 조회 오류:', error);
throw error;
}
}
// 사용 예제
// 이름이 '홍길동'인 사용자 조회
findOneUser(collection, { name: '홍길동' })
.then(user => console.log('조회된 사용자:', user));
// 나이가 25 이상인 사용자 조회 (이름과 이메일만 포함)
findUsers(collection, { age: { $gte: 25 } }, { projection: { name: 1, email: 1, _id: 0 } })
.then(users => console.log('조회된 사용자 목록:', users));
// 페이지네이션 예제
findUsers(collection, {}, { skip: 10, limit: 10, sort: { age: -1 } })
.then(users => console.log('페이지네이션된 결과:', users));수정 (Update)
// 단일 문서 업데이트
async function updateOneUser(collection, filter, update) {
try {
const result = await collection.updateOne(filter, update);
console.log(`${result.matchedCount}개 문서 일치, ${result.modifiedCount}개 문서 수정됨`);
return result;
} catch (error) {
console.error('문서 업데이트 오류:', error);
throw error;
}
}
// 여러 문서 업데이트
async function updateManyUsers(collection, filter, update) {
try {
const result = await collection.updateMany(filter, update);
console.log(`${result.matchedCount}개 문서 일치, ${result.modifiedCount}개 문서 수정됨`);
return result;
} catch (error) {
console.error('문서 업데이트 오류:', error);
throw error;
}
}
// 사용 예제
// 홍길동의 나이 업데이트
updateOneUser(
collection,
{ name: '홍길동' },
{ $set: { age: 31 }, $currentDate: { lastModified: true } }
)
.then(result => console.log('업데이트 결과:', result));
// 25세 이상 모든 사용자에게 'adult' 속성 추가
updateManyUsers(
collection,
{ age: { $gte: 25 } },
{ $set: { adult: true } }
)
.then(result => console.log('업데이트 결과:', result));삭제 (Delete)
// 단일 문서 삭제
async function deleteOneUser(collection, filter) {
try {
const result = await collection.deleteOne(filter);
console.log(`${result.deletedCount}개 문서 삭제됨`);
return result;
} catch (error) {
console.error('문서 삭제 오류:', error);
throw error;
}
}
// 여러 문서 삭제
async function deleteManyUsers(collection, filter) {
try {
const result = await collection.deleteMany(filter);
console.log(`${result.deletedCount}개 문서 삭제됨`);
return result;
} catch (error) {
console.error('문서 삭제 오류:', error);
throw error;
}
}
// 사용 예제
// 이메일이 'hong@example.com'인 사용자 삭제
deleteOneUser(collection, { email: 'hong@example.com' })
.then(result => console.log('삭제 결과:', result));
// 나이가 20 미만인 모든 사용자 삭제
deleteManyUsers(collection, { age: { $lt: 20 } })
.then(result => console.log('삭제 결과:', result));스키마 설계
MongoDB는 스키마가 없는(schema-less) 데이터베이스지만, 애플리케이션 레벨에서 스키마를 설계하는 것이 중요합니다. Mongoose를 사용하면 Node.js에서 MongoDB 스키마를 정의할 수 있습니다.
Mongoose 스키마 설계
const mongoose = require('mongoose');
// Mongoose 연결
mongoose.connect('mongodb://localhost:27017/testdb', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('Mongoose로 MongoDB에 연결되었습니다'))
.catch(err => console.error('Mongoose 연결 오류:', err));
// 사용자 스키마 정의
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
trim: true,
validate: {
validator: function(v) {
return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v);
},
message: props => `${props.value}는 유효한 이메일 주소가 아닙니다`
}
},
password: {
type: String,
required: true,
minlength: 6
},
age: {
type: Number,
min: 0,
max: 120,
default: 18
},
isActive: {
type: Boolean,
default: true
},
role: {
type: String,
enum: ['user', 'admin', 'editor'],
default: 'user'
},
address: {
street: String,
city: String,
zipCode: String,
country: String
},
interests: [String],
createdAt: {
type: Date,
default: Date.now
},
lastUpdated: Date
}, {
timestamps: true,
collection: 'users'
});
// 가상 속성 추가
userSchema.virtual('fullName').get(function() {
return `${this.name.first} ${this.name.last}`;
});
// 인스턴스 메서드 추가
userSchema.methods.isAdult = function() {
return this.age >= 18;
};
// 정적 메서드 추가
userSchema.statics.findByEmail = function(email) {
return this.findOne({ email });
};
// 중간 처리 추가 (미들웨어)
userSchema.pre('save', function(next) {
this.lastUpdated = new Date();
next();
});
// 모델 생성
const User = mongoose.model('User', userSchema);
module.exports = User;Mongoose를 사용한 CRUD 작업
const User = require('./models/User');
// 생성
async function createUser(userData) {
try {
const user = new User(userData);
await user.save();
return user;
} catch (error) {
console.error('사용자 생성 오류:', error);
throw error;
}
}
// 읽기
async function findAllUsers() {
return await User.find({});
}
async function findUserById(id) {
return await User.findById(id);
}
async function findUserByEmail(email) {
return await User.findByEmail(email); // 정적 메서드 사용
}
// 업데이트
async function updateUser(id, updateData) {
return await User.findByIdAndUpdate(id, updateData, { new: true });
}
// 삭제
async function deleteUser(id) {
return await User.findByIdAndDelete(id);
}
// 사용 예제
// 사용자 생성
createUser({
name: '장민수',
email: 'jang@example.com',
password: 'securepassword',
age: 35,
address: {
city: '서울',
country: '대한민국'
},
interests: ['프로그래밍', '독서', '여행']
})
.then(user => console.log('생성된 사용자:', user))
.catch(err => console.error('오류:', err));내장 문서와 참조 관계
MongoDB에서는 두 가지 방식으로 관련 데이터를 모델링할 수 있습니다:
1. 내장 문서 (Embedded Documents)
// 게시물 스키마 (댓글이 내장된 형태)
const postSchema = new mongoose.Schema({
title: String,
content: String,
author: {
name: String,
email: String
},
comments: [{
text: String,
author: String,
createdAt: {
type: Date,
default: Date.now
}
}],
createdAt: {
type: Date,
default: Date.now
}
});
const Post = mongoose.model('Post', postSchema);2. 참조 관계 (References)
// 사용자 스키마
const userSchema = new mongoose.Schema({
name: String,
email: String,
// 다른 필드들...
});
const User = mongoose.model('User', userSchema);
// 게시물 스키마 (사용자 참조)
const postSchema = new mongoose.Schema({
title: String,
content: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
createdAt: {
type: Date,
default: Date.now
}
});
const Post = mongoose.model('Post', postSchema);
// 댓글 스키마 (게시물과 사용자 참조)
const commentSchema = new mongoose.Schema({
text: String,
post: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
createdAt: {
type: Date,
default: Date.now
}
});
const Comment = mongoose.model('Comment', commentSchema);참조 데이터 조회 (Populate)
// 게시물과 작성자 정보 함께 조회
async function findPostWithAuthor(postId) {
return await Post.findById(postId)
.populate('author', 'name email -_id') // 작성자의 이름과 이메일만 조회, _id 제외
.exec();
}
// 게시물, 작성자, 댓글 및 댓글 작성자 조회
async function findPostWithCommentsAndAuthors(postId) {
const post = await Post.findById(postId)
.populate('author', 'name email')
.exec();
const comments = await Comment.find({ post: postId })
.populate('author', 'name')
.exec();
return { post, comments };
}인덱싱
인덱스는 데이터베이스 쿼리의 성능을 향상시킵니다. MongoDB는 다양한 유형의 인덱스를 지원합니다.
인덱스 생성
// 단일 필드 인덱스
db.users.createIndex({ email: 1 }); // 1은 오름차순, -1은 내림차순
// 복합 인덱스
db.users.createIndex({ age: 1, name: 1 });
// 고유 인덱스
db.users.createIndex({ email: 1 }, { unique: true });
// TTL (Time-To-Live) 인덱스
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }); // 1시간 후 문서 자동 삭제
// 텍스트 인덱스
db.articles.createIndex({ title: 'text', content: 'text' });
// 지리공간 인덱스
db.places.createIndex({ location: '2dsphere' });
// 부분 인덱스
db.users.createIndex(
{ email: 1 },
{ partialFilterExpression: { isActive: true } }
);Mongoose에서 인덱스 정의
const userSchema = new mongoose.Schema({
name: String,
email: {
type: String,
unique: true // 고유 인덱스
},
isActive: Boolean,
location: {
type: {
type: String,
enum: ['Point'],
default: 'Point'
},
coordinates: {
type: [Number], // [경도, 위도]
required: true
}
}
});
// 복합 인덱스
userSchema.index({ name: 1, email: 1 });
// 지리공간 인덱스
userSchema.index({ location: '2dsphere' });
// 텍스트 인덱스
userSchema.index({ name: 'text', bio: 'text' });
const User = mongoose.model('User', userSchema);인덱스 관리
// 컬렉션의 모든 인덱스 조회
db.users.getIndexes();
// 인덱스 삭제
db.users.dropIndex({ email: 1 });
// 모든 인덱스 삭제 (primary key인 _id 인덱스 제외)
db.users.dropIndexes();애그리게이션
MongoDB의 집계 프레임워크를 사용하면 데이터를 그룹화하고 계산할 수 있습니다.
애그리게이션 파이프라인
// 연령대별 사용자 수 계산
db.users.aggregate([
// 스테이지 1: 연령대 필드 추가
{
$addFields: {
ageGroup: {
$switch: {
branches: [
{ case: { $lt: ["$age", 20] }, then: "10대" },
{ case: { $lt: ["$age", 30] }, then: "20대" },
{ case: { $lt: ["$age", 40] }, then: "30대" },
{ case: { $lt: ["$age", 50] }, then: "40대" }
],
default: "50대 이상"
}
}
}
},
// 스테이지 2: 연령대별로 그룹화하고 수 계산
{
$group: {
_id: "$ageGroup",
count: { $sum: 1 },
avgAge: { $avg: "$age" }
}
},
// 스테이지 3: 결과 정렬
{
$sort: { _id: 1 }
}
]);Node.js에서 애그리게이션 사용
async function getUserStatsByAgeGroup(collection) {
return await collection.aggregate([
{
$match: { isActive: true } // 활성 사용자만 필터링
},
{
$group: {
_id: {
$concat: [
{ $toString: { $subtract: [{ $floor: { $divide: ["$age", 10] } }, 0] } },
"0대"
]
},
count: { $sum: 1 },
avgAge: { $avg: "$age" },
minAge: { $min: "$age" },
maxAge: { $max: "$age" },
users: { $push: { name: "$name", age: "$age" } }
}
},
{
$sort: { "_id": 1 }
}
]).toArray();
}
// 사용 예제
getUserStatsByAgeGroup(collection)
.then(results => console.log('연령대별 통계:', results))
.catch(err => console.error('오류:', err));주요 애그리게이션 연산자
// $match: 문서 필터링
{ $match: { age: { $gte: 18 } } }
// $group: 문서 그룹화
{ $group: { _id: "$country", total: { $sum: 1 } } }
// $sort: 결과 정렬
{ $sort: { total: -1 } }
// $limit: 결과 개수 제한
{ $limit: 10 }
// $skip: 결과 건너뛰기
{ $skip: 10 }
// $project: 필드 선택 또는 제외
{ $project: { name: 1, age: 1, _id: 0 } }
// $unwind: 배열 필드 분해
{ $unwind: "$tags" }
// $lookup: 다른 컬렉션 조인
{
$lookup: {
from: "comments",
localField: "_id",
foreignField: "postId",
as: "comments"
}
}
// $facet: 여러 애그리게이션 파이프라인 병렬 실행
{
$facet: {
"byAge": [
{ $match: { age: { $gte: 20 } } },
{ $group: { _id: "$age", count: { $sum: 1 } } }
],
"byCountry": [
{ $group: { _id: "$country", count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: 5 }
]
}
}트랜잭션
MongoDB는 버전 4.0부터 멀티 도큐먼트 트랜잭션을 지원합니다.
트랜잭션 사용하기
async function transferMoney(client, fromAccountId, toAccountId, amount) {
// 세션 시작
const session = client.startSession();
try {
// 트랜잭션 시작
session.startTransaction();
const accounts = client.db('bankdb').collection('accounts');
// 출금 계좌에서 금액 차감
const fromResult = await accounts.updateOne(
{ _id: fromAccountId },
{ $inc: { balance: -amount } },
{ session }
);
if (fromResult.modifiedCount !== 1) {
throw new Error('출금 계좌 업데이트 실패');
}
// 입금 계좌에 금액 추가
const toResult = await accounts.updateOne(
{ _id: toAccountId },
{ $inc: { balance: amount } },
{ session }
);
if (toResult.modifiedCount !== 1) {
throw new Error('입금 계좌 업데이트 실패');
}
// 송금 내역 기록
await client.db('bankdb').collection('transactions').insertOne({
from: fromAccountId,
to: toAccountId,
amount,
date: new Date()
}, { session });
// 트랜잭션 커밋
await session.commitTransaction();
console.log('송금 성공');
} catch (error) {
// 오류 발생 시 롤백
await session.abortTransaction();
console.error('송금 실패, 트랜잭션 롤백됨:', error);
throw error;
} finally {
// 세션 종료
session.endSession();
}
}
// 사용 예제
transferMoney(client, '607f1f77bcf86cd799439011', '607f1f77bcf86cd799439022', 1000)
.then(() => console.log('송금 프로세스 완료'))
.catch(err => console.error('송금 프로세스 오류:', err));Mongoose에서 트랜잭션 사용하기
const mongoose = require('mongoose');
async function createOrderWithProducts(userId, products, shippingInfo) {
// 세션 시작
const session = await mongoose.startSession();
session.startTransaction();
try {
const Order = mongoose.model('Order');
const Product = mongoose.model('Product');
const User = mongoose.model('User');
// 주문 생성
const newOrder = new Order({
user: userId,
products: products.map(p => ({
product: p.id,
quantity: p.quantity,
price: p.price
})),
shippingInfo,
totalAmount: products.reduce((sum, p) => sum + (p.price * p.quantity), 0)
});
await newOrder.save({ session });
// 상품 재고 업데이트
for (const product of products) {
const updatedProduct = await Product.findByIdAndUpdate(
product.id,
{ $inc: { stock: -product.quantity } },
{ new: true, session }
);
if (updatedProduct.stock < 0) {
throw new Error(`상품 ${product.id}의 재고가 부족합니다`);
}
}
// 사용자 주문 목록 업데이트
await User.findByIdAndUpdate(
userId,
{ $push: { orders: newOrder._id } },
{ session }
);
// 트랜잭션 커밋
await session.commitTransaction();
return newOrder;
} catch (error) {
// 롤백
await session.abortTransaction();
throw error;
} finally {
// 세션 종료
session.endSession();
}
}성능 최적화
쿼리 성능 향상 팁
// 1. 적절한 인덱스 사용
db.users.createIndex({ email: 1, name: 1 });
// 2. 프로젝션을 사용하여 필요한 필드만 조회
db.users.find({ age: { $gte: 18 } }, { name: 1, email: 1, _id: 0 });
// 3. limit()를 사용하여 결과 크기 제한
db.users.find().limit(100);
// 4. skip()과 limit()을 함께 사용하여 페이지네이션 구현
db.users.find().skip(20).limit(10); // 3번째 페이지 (페이지당 10개)
// 5. sort()를 인덱스가 있는 필드로 수행
db.users.find().sort({ email: 1 }); // email 필드에 인덱스가 있어야 함
// 6. explain()을 사용하여 쿼리 분석
db.users.find({ age: { $gte: 30 } }).explain("executionStats");인덱스 성능 최적화
// 1. 복합 인덱스의 순서 최적화 (가장 자주 필터링되는 필드를 먼저 배치)
// "name으로 필터링 + age로 정렬"하는 쿼리가 많다면:
db.users.createIndex({ name: 1, age: 1 });
// 2. 부분 인덱스 사용으로 인덱스 크기 최적화
// 활성 사용자만 인덱싱
db.users.createIndex(
{ email: 1 },
{ partialFilterExpression: { isActive: true } }
);
// 3. 백그라운드에서 인덱스 생성 (프로덕션 환경에서 부하 감소)
db.users.createIndex({ lastLogin: 1 }, { background: true });
// 4. 희소 인덱스 사용 (필드가 있는 문서만 인덱싱)
db.users.createIndex({ phoneNumber: 1 }, { sparse: true });
// 5. 사용되지 않는 인덱스 정기적으로 확인 및 제거
db.users.aggregate([{ $indexStats: {} }]);쓰기 연산 최적화
// 1. 대량 삽입 사용
db.users.insertMany([
{ name: "user1", age: 25 },
{ name: "user2", age: 30 },
// ...
], { ordered: false }); // 순서에 상관없이 병렬 처리
// 2. 업데이트 연산 최적화 (필요한 필드만 업데이트)
// 좋지 않은 방법 (전체 문서 교체)
db.users.updateOne({ _id: userId }, { name: "New Name", age: 35 });
// 좋은 방법 (특정 필드만 업데이트)
db.users.updateOne({ _id: userId }, { $set: { name: "New Name" } });
// 3. 다중 업데이트 대신 bulkWrite 사용
db.users.bulkWrite([
{ updateOne: { filter: { _id: id1 }, update: { $set: { status: "active" } } } },
{ updateOne: { filter: { _id: id2 }, update: { $set: { status: "inactive" } } } },
{ updateOne: { filter: { _id: id3 }, update: { $set: { status: "active" } } } }
]);데이터 모델링 최적화
// 1. 자주 함께 조회되는 데이터는 내장 문서로 저장
// 좋은 모델링 예시 (사용자 정보와 주소를 함께 조회하는 경우가 많을 때)
{
_id: ObjectId("..."),
name: "홍길동",
email: "hong@example.com",
address: {
street: "서울특별시 강남구 테헤란로 123",
city: "서울",
zipCode: "06234",
country: "대한민국"
}
}
// 2. 대용량 배열 내장보다는 별도 컬렉션과 참조 사용
// 나쁜 예: 수천 개의 댓글을 포함한 게시물
{
_id: ObjectId("..."),
title: "인기 게시물",
content: "...",
comments: [
{ text: "좋은 글이네요", author: "user1", date: ... },
{ text: "감사합니다", author: "user2", date: ... },
// ... 수천 개의 댓글
]
}
// 좋은 예: 댓글을 별도 컬렉션으로 분리
// posts 컬렉션
{
_id: ObjectId("..."),
title: "인기 게시물",
content: "...",
commentCount: 2345
}
// comments 컬렉션
{
_id: ObjectId("..."),
postId: ObjectId("게시물 ID"),
text: "좋은 글이네요",
author: "user1",
date: ...
}
// 3. 접근 패턴에 따른 데이터 복제 (비정규화)
// 여러 컬렉션에서 동일한 데이터가 필요할 때
// users 컬렉션
{
_id: ObjectId("..."),
name: "홍길동",
email: "hong@example.com"
}
// orders 컬렉션 (사용자 이름도 저장)
{
_id: ObjectId("..."),
userId: ObjectId("사용자 ID"),
userName: "홍길동", // 복제된 데이터 (비정규화)
products: [...],
total: 15000
}보안 설정
인증 활성화
1. MongoDB 설정 파일 (mongod.conf)에 인증 추가
security:
authorization: enabled2. 관리자 사용자 생성
// 관리자 데이터베이스에 연결
use admin
// 관리자 사용자 생성
db.createUser({
user: "adminUser",
pwd: "securePassword",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})3. 특정 데이터베이스 사용자 생성
use myDatabase
db.createUser({
user: "appUser",
pwd: "appPassword",
roles: [
{ role: "readWrite", db: "myDatabase" },
{ role: "read", db: "reportingDatabase" }
]
})4. 인증을 사용하여 연결
// MongoDB 연결 문자열 (인증 포함)
const uri = 'mongodb://appUser:appPassword@localhost:27017/myDatabase';
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});역할 기반 접근 제어 (RBAC)
MongoDB는 다음과 같은 내장 역할을 제공합니다:
데이터베이스 사용자 역할:
read: 데이터 읽기만 가능readWrite: 데이터 읽기와 쓰기 가능
데이터베이스 관리 역할:
dbAdmin: 스키마 관련 작업 가능userAdmin: 사용자 및 역할 관리 가능dbOwner: dbAdmin, userAdmin, readWrite 역할 모두 포함
클러스터 관리 역할:
clusterAdmin: 가장 높은 클러스터 관리 권한clusterManager: 관리 및 모니터링 작업clusterMonitor: 모니터링 도구 읽기 권한hostManager: 서버 추가 및 제거 기능
백업/복원 역할:
backup: 백업에 필요한 권한restore: 복원에 필요한 권한
// 커스텀 역할 생성 예제
db.createRole({
role: "reportingRole",
privileges: [
{
resource: { db: "reporting", collection: "metrics" },
actions: [ "find" ]
}
],
roles: [
{ role: "read", db: "reporting" }
]
})
// 사용자에게 역할 할당
db.grantRolesToUser("reportUser", [
{ role: "reportingRole", db: "admin" }
])TLS/SSL 암호화 설정
1. SSL 인증서 생성
# 자체 서명된 인증서 생성
mkdir -p /etc/ssl/mongodb
cd /etc/ssl/mongodb
# 개인 키 생성
openssl genrsa -out mongodb.key 4096
# 인증서 생성
openssl req -new -x509 -key mongodb.key -out mongodb.crt -days 3652. MongoDB 설정 파일 수정
net:
port: 27017
bindIp: 0.0.0.0
ssl:
mode: requireSSL
PEMKeyFile: /etc/ssl/mongodb/mongodb.pem3. SSL을 사용하여 연결
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
ssl: true,
sslValidate: true,
sslCA: '/path/to/ca.crt' // 필요한 경우
});네트워크 보안
1. IP 화이트리스트 설정
# mongod.conf
net:
port: 27017
bindIp: 127.0.0.1,192.168.1.100 # 로컬호스트와 특정 IP만 접근 허용2. 방화벽 설정
# Ubuntu에서 UFW 방화벽 설정
sudo ufw allow from 192.168.1.0/24 to any port 27017
# CentOS/RHEL에서 firewalld 설정
sudo firewall-cmd --permanent --add-port=27017/tcp --zone=trusted
sudo firewall-cmd --permanent --add-source=192.168.1.0/24 --zone=trusted
sudo firewall-cmd --reload모니터링 및 관리
기본 모니터링 명령어
// 서버 상태 확인
db.serverStatus()
// 데이터베이스 통계
db.stats()
// 컬렉션 통계
db.users.stats()
// 현재 실행 중인 작업
db.currentOp()
// 프로파일링 설정 (모든 느린 쿼리 기록)
db.setProfilingLevel(1, 100) // 100ms 이상 소요되는 쿼리 기록
// 프로파일링 결과 조회
db.system.profile.find().sort({ millis: -1 }).limit(10)MongoDB Compass를 통한 모니터링
MongoDB Compass는 다음 기능을 제공합니다:
- 실시간 서버 통계 모니터링
- 쿼리 성능 분석
- 인덱스 사용 통계
- 컬렉션 데이터 시각화
- 스키마 분석
MongoDB Atlas 모니터링
MongoDB Atlas 클라우드 서비스는 다음과 같은 모니터링 기능을 제공합니다:
- 실시간 성능 대시보드
- 알림 설정
- 성능 권장사항
- 로그 분석
- 쿼리 프로파일러
백업 및 복원
1. mongodump 및 mongorestore 사용
# 백업 수행
mongodump --uri="mongodb://localhost:27017/mydb" --out=/backup/mongodb/$(date +%Y-%m-%d)
# 복원 수행
mongorestore --uri="mongodb://localhost:27017/mydb" --dir=/backup/mongodb/2023-08-15/mydb2. Node.js 스크립트를 사용한 자동 백업
const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
// 백업 디렉터리 생성
const backupDir = `/backup/mongodb/${new Date().toISOString().slice(0, 10)}`;
if (!fs.existsSync(backupDir)) {
fs.mkdirSync(backupDir, { recursive: true });
}
// mongodump 명령 실행
const mongoDumpCommand = `mongodump --uri="mongodb://username:password@localhost:27017/mydb" --out=${backupDir}`;
exec(mongoDumpCommand, (error, stdout, stderr) => {
if (error) {
console.error(`백업 오류: ${error.message}`);
return;
}
if (stderr) {
console.error(`백업 경고: ${stderr}`);
return;
}
console.log(`백업 성공: ${backupDir}`);
// 오래된 백업 삭제 (30일 이상)
const backupRoot = '/backup/mongodb';
fs.readdir(backupRoot, (err, files) => {
if (err) {
console.error(`디렉터리 읽기 오류: ${err.message}`);
return;
}
const now = new Date();
files.forEach(file => {
const filePath = path.join(backupRoot, file);
const stat = fs.statSync(filePath);
// 디렉터리이고, 30일 이상 된 백업인지 확인
if (stat.isDirectory() && /^\d{4}-\d{2}-\d{2}$/.test(file)) {
const fileDate = new Date(file);
const diffDays = Math.ceil((now - fileDate) / (1000 * 60 * 60 * 24));
if (diffDays > 30) {
console.log(`오래된 백업 삭제: ${filePath}`);
fs.rmdirSync(filePath, { recursive: true });
}
}
});
});
});데이터 마이그레이션
const { MongoClient } = require('mongodb');
async function migrateData() {
const sourceUri = 'mongodb://source-server:27017/sourcedb';
const targetUri = 'mongodb://target-server:27017/targetdb';
const sourceClient = new MongoClient(sourceUri);
const targetClient = new MongoClient(targetUri);
try {
await sourceClient.connect();
await targetClient.connect();
const sourceDB = sourceClient.db();
const targetDB = targetClient.db();
// 컬렉션 목록 가져오기
const collections = await sourceDB.listCollections().toArray();
for (const collInfo of collections) {
const collName = collInfo.name;
console.log(`${collName} 컬렉션 마이그레이션 중...`);
const sourceCollection = sourceDB.collection(collName);
const targetCollection = targetDB.collection(collName);
// 청크 단위로 데이터 마이그레이션 (메모리 사용량 최적화)
const batchSize = 1000;
let processed = 0;
const totalCount = await sourceCollection.countDocuments();
for (let skip = 0; skip < totalCount; skip += batchSize) {
const docs = await sourceCollection.find({})
.skip(skip)
.limit(batchSize)
.toArray();
if (docs.length > 0) {
await targetCollection.insertMany(docs);
processed += docs.length;
console.log(`${collName}: ${processed}/${totalCount} 문서 처리됨`);
}
}
// 인덱스 복제
const indexes = await sourceCollection.indexes();
for (const index of indexes) {
// _id_ 인덱스는 자동 생성되므로 건너뜀
if (index.name !== '_id_') {
const indexSpec = {};
for (const key in index.key) {
indexSpec[key] = index.key[key];
}
// 인덱스 옵션 설정
const options = {};
if (index.unique) options.unique = true;
if (index.sparse) options.sparse = true;
if (index.expireAfterSeconds) options.expireAfterSeconds = index.expireAfterSeconds;
await targetCollection.createIndex(indexSpec, options);
console.log(`${collName} 컬렉션에 인덱스 생성됨: ${index.name}`);
}
}
}
console.log('데이터 마이그레이션 완료!');
} catch (error) {
console.error('마이그레이션 오류:', error);
} finally {
await sourceClient.close();
await targetClient.close();
}
}
migrateData();데이터베이스 유지 관리
// 1. 데이터베이스 압축 (디스크 공간 회수)
db.runCommand({ compact: 'users' });
// 2. 컬렉션 재생성 (파편화 제거)
db.runCommand({ convertToCapped: 'logs', size: 1048576 }); // 로그 컬렉션을 1MB로 제한
// 3. 데이터베이스 수리
db.repairDatabase();
// 4. 샤드 밸런싱 확인
sh.status();
// 5. 인덱스 재구축
db.users.reIndex();이 문서는 MongoDB의 기본 개념부터 고급 기술까지 다루고 있습니다. 더 많은 정보는 MongoDB 공식 문서를 참조하세요.
Happy Coding!