본문으로 건너뛰기
기술 노트 목록

MongoDB 컬렉션 관리

Database/MongoDB. 2024-12-13에 씀. 3분 분량

Database, MongoDB

MongoDB 컬렉션 관리

createCollection()

설명

새로운 컬렉션을 생성합니다.

구문

db.createCollection(
    <name>,
    {
        capped: <boolean>,
        size: <number>,
        max: <number>,
        validator: <document>,
        validationLevel: <string>,
        validationAction: <string>
    }
)

예제

// 기본 컬렉션 생성
db.createCollection("users")

// 제한된 크기의 캡드 컬렉션 생성
db.createCollection("logs", {
    capped: true,
    size: 5242880,  // 5MB
    max: 5000       // 최대 5000개 문서
})

// 유효성 검사 규칙이 있는 컬렉션 생성
db.createCollection("products", {
    validator: {
        $jsonSchema: {
            bsonType: "object",
            required: ["name", "price"],
            properties: {
                name: {
                    bsonType: "string",
                    description: "must be a string and is required"
                },
                price: {
                    bsonType: "number",
                    minimum: 0,
                    description: "must be a positive number and is required"
                }
            }
        }
    },
    validationLevel: "strict",
    validationAction: "error"
})

drop()

설명

컬렉션을 삭제합니다.

구문

db.collection.drop()

예제

// users 컬렉션 삭제
db.users.drop()

renameCollection()

설명

컬렉션의 이름을 변경합니다.

구문

db.collection.renameCollection(
    <target name>,
    <drop target if exists>
)

예제

// users 컬렉션을 customers로 이름 변경
db.users.renameCollection("customers", true)

stats()

설명

컬렉션의 통계 정보를 조회합니다.

구문

db.collection.stats()

예제

// users 컬렉션의 통계 정보 조회
db.users.stats()

컬렉션 관리 고급 기능

유효성 검사 규칙 수정

// 기존 컬렉션에 유효성 검사 규칙 추가
db.runCommand({
    collMod: "products",
    validator: {
        $jsonSchema: {
            bsonType: "object",
            required: ["name", "price", "category"],
            properties: {
                name: {
                    bsonType: "string",
                    description: "must be a string and is required"
                },
                price: {
                    bsonType: "number",
                    minimum: 0,
                    description: "must be a positive number and is required"
                },
                category: {
                    bsonType: "string",
                    description: "must be a string and is required"
                }
            }
        }
    },
    validationLevel: "moderate"
})

캡드 컬렉션 관리

// 캡드 컬렉션 생성 (로그 저장용)
db.createCollection("systemLogs", {
    capped: true,
    size: 10485760,  // 10MB
    max: 10000
})

// 캡드 컬렉션 여부 확인
db.systemLogs.isCapped()

// 컬렉션을 캡드 컬렉션으로 변환
db.runCommand({
    convertToCapped: "normalCollection",
    size: 10485760
})

컬렉션 옵션 조회

// 컬렉션 옵션 조회
db.getCollectionInfos({ name: "products" })

시간 기반 데이터 관리

// TTL 인덱스를 사용한 문서 자동 삭제
db.sessions.createIndex(
    { lastModifiedDate: 1 },
    { expireAfterSeconds: 3600 }  // 1시간 후 만료
)

컬렉션 성능 최적화

인덱스 관리

// 컬렉션의 모든 인덱스 조회
db.collection.getIndexes()

// 인덱스 사용 통계 확인
db.collection.aggregate([
    { $indexStats: {} }
])

컬렉션 조각화 관리

// 컬렉션 조각화 상태 확인
db.runCommand({
    collStats: "users"
})

// 컬렉션 압축
db.runCommand({
    compact: "users"
})

저장소 최적화

// 컬렉션 데이터 크기 분석
db.users.stats().size
db.users.stats().storageSize

// 컬렉션 문서 수 확인
db.users.count()
db.users.estimatedDocumentCount()

다른 기술 노트 보기