MongoDB 인덱스 연산
createIndex()
설명
컬렉션에 새로운 인덱스를 생성합니다.
구문
db.collection.createIndex(
<key and index type specification>,
<options>
)예제
// 단일 필드 인덱스
db.users.createIndex({ email: 1 })
// 복합 인덱스
db.users.createIndex({ name: 1, age: -1 })
// 유니크 인덱스
db.users.createIndex(
{ email: 1 },
{ unique: true }
)
// TTL 인덱스
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
)
// 텍스트 인덱스
db.articles.createIndex(
{ content: "text" }
)createIndexes()
설명
컬렉션에 여러 인덱스를 동시에 생성합니다.
구문
db.collection.createIndexes([
{ key: <key and index type specification>, name: <index name>, <other options> },
{ key: <key and index type specification>, name: <index name>, <other options> },
...
])예제
db.users.createIndexes([
{ key: { email: 1 }, name: "email_idx", unique: true },
{ key: { age: 1 }, name: "age_idx" },
{ key: { name: 1, country: 1 }, name: "name_country_idx" }
])dropIndex()
설명
지정된 인덱스를 삭제합니다.
구문
db.collection.dropIndex(index)예제
// 인덱스 이름으로 삭제
db.users.dropIndex("email_1")
// 인덱스 키 명세로 삭제
db.users.dropIndex({ email: 1 })dropIndexes()
설명
컬렉션의 모든 인덱스를 삭제합니다. _id 인덱스는 유지됩니다.
구문
db.collection.dropIndexes()예제
db.users.dropIndexes()getIndexes()
설명
컬렉션의 모든 인덱스 정보를 조회합니다.
구문
db.collection.getIndexes()예제
db.users.getIndexes()인덱스 속성
인덱스 타입
- 단일 필드 인덱스
- 복합 인덱스
- 다중키 인덱스 (배열)
- 지리공간 인덱스
- 텍스트 인덱스
- 해시 인덱스
인덱스 옵션
{
unique: <boolean>, // 고유 값 인덱스
partialFilterExpression: <document>, // 부분 인덱스
sparse: <boolean>, // 희소 인덱스
expireAfterSeconds: <number>, // TTL 인덱스
weights: <document>, // 텍스트 인덱스 가중치
default_language: <string>, // 텍스트 인덱스 기본 언어
language_override: <string> // 언어 필드 지정
}인덱스 사용 모범 사례
- 자주 사용되는 쿼리 패턴에 맞춰 인덱스 생성
- 복합 인덱스 생성 시 선택도가 높은 필드를 앞에 배치
- 불필요한 인덱스 제거로 쓰기 성능 최적화
- 인덱스 크기가 RAM에 맞도록 관리
- 백그라운드에서 인덱스 생성하여 운영 중 성능 영향 최소화
인덱스 생성 시 고려사항
// 백그라운드 인덱스 생성
db.users.createIndex(
{ email: 1 },
{ background: true }
)
// 부분 인덱스 생성
db.users.createIndex(
{ age: 1 },
{
partialFilterExpression: {
age: { $gt: 18 }
}
}
)
// 희소 인덱스 생성
db.users.createIndex(
{ email: 1 },
{ sparse: true }
)