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

MongoDB 데이터베이스 관리

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

Database, MongoDB

MongoDB 데이터베이스 관리

사용자 관리

createUser()

설명

새로운 데이터베이스 사용자를 생성합니다.

구문

db.createUser({
    user: <username>,
    pwd: <password>,
    roles: [<role1>, <role2>, ...]
})

예제

// 관리자 사용자 생성
db.createUser({
    user: "admin",
    pwd: "secure_password",
    roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase"]
})

// 특정 데이터베이스의 읽기/쓰기 권한을 가진 사용자 생성
db.createUser({
    user: "appUser",
    pwd: "app_password",
    roles: [
        { role: "readWrite", db: "myApp" },
        { role: "read", db: "reporting" }
    ]
})

dropUser()

설명

데이터베이스 사용자를 삭제합니다.

구문

db.dropUser(<username>)

예제

// 사용자 삭제
db.dropUser("appUser")

역할 관리

createRole()

설명

새로운 사용자 정의 역할을 생성합니다.

구문

db.createRole({
    role: <role_name>,
    privileges: [<privilege1>, <privilege2>, ...],
    roles: [<role1>, <role2>, ...]
})

예제

// 커스텀 역할 생성
db.createRole({
    role: "myCustomRole",
    privileges: [
        {
            resource: { db: "myApp", collection: "" },
            actions: ["find", "update"]
        }
    ],
    roles: ["read"]
})

dropRole()

설명

사용자 정의 역할을 삭제합니다.

구문

db.dropRole(<role_name>)

예제

// 역할 삭제
db.dropRole("myCustomRole")

권한 관리

grantRolesToUser()

설명

사용자에게 역할을 부여합니다.

구문

db.grantRolesToUser(
    <username>,
    [<role1>, <role2>, ...]
)

예제

// 사용자에게 추가 역할 부여
db.grantRolesToUser(
    "appUser",
    ["readWrite"]
)

revokeRolesFromUser()

설명

사용자로부터 역할을 제거합니다.

구문

db.revokeRolesFromUser(
    <username>,
    [<role1>, <role2>, ...]
)

예제

// 사용자로부터 역할 제거
db.revokeRolesFromUser(
    "appUser",
    ["readWrite"]
)

보안 관리

인증 활성화

// mongod.conf 설정
security:
    authorization: enabled

SSL/TLS 설정

// mongod.conf SSL 설정
net:
    ssl:
        mode: requireSSL
        PEMKeyFile: /path/to/mongodb.pem
        CAFile: /path/to/ca.pem

모니터링 및 진단

데이터베이스 상태 확인

// 데이터베이스 상태 조회
db.serverStatus()

// 현재 작업 확인
db.currentOp()

// 시스템 프로파일링 설정
db.setProfilingLevel(1, { slowms: 100 })

백업 및 복구

// 데이터베이스 백업
mongodump --db myDatabase --out /backup/path

// 데이터베이스 복구
mongorestore --db myDatabase /backup/path/myDatabase

// 특정 컬렉션 백업
mongodump --db myDatabase --collection myCollection --out /backup/path

// 특정 컬렉션 복구
mongorestore --db myDatabase --collection myCollection /backup/path/myDatabase/myCollection.bson

성능 최적화

시스템 프로파일링

// 프로파일링 활성화
db.setProfilingLevel(2)  // 모든 작업 프로파일링

// 느린 쿼리 프로파일링
db.setProfilingLevel(1, { slowms: 100 })

// 프로파일링 데이터 조회
db.system.profile.find().pretty()

메모리 사용량 모니터링

// 메모리 통계 확인
db.serverStatus().mem

// WiredTiger 캐시 통계
db.serverStatus().wiredTiger.cache

데이터베이스 유지보수

// 데이터베이스 복구
db.repairDatabase()

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

// 데이터베이스 통계
db.stats()

다른 기술 노트 보기