Index
MongoDB에서 데이터 쿼리를 더욱 효율적으로 할 수 있게 한다.
Document 필드에 index를 걸면, 데이터의 설정한 키 값을 가지고 document들을 가리키는 포인터 값으로 이뤄진 B-Tree를 만든다.
이 B-Tree에서 Binary Search를 통해 쿼리 속도를 매우 빠르게 향상 시킬 수 있다.
Index의 종류
Default _id Index
모든 MongoDB의 컬렉션은 기본적으로 _id 필드에 인덱스가 존재하며, unique하다. 이는 MongoDB 클라이언트가 같은 _id를 가진 문서를 중복적으로 추가하는 것을 방지한다.
Single Field Indexes
_id 인덱스 이외에도 원하는 값을 단일 필드 인덱스로 지정할 수 있다.
이미지출처: https://docs.mongodb.com/manual/core/index-single/
Single Field Indexes — MongoDB Manual
Docs Home → MongoDB ManualMongoDB provides complete support for indexes on any field in a collection of documents. By default, all collections have an index on the _id field, and applications and users may add additional indexes to support important quer
docs.mongodb.com
Compound Indexes
두개 이상의 필드를 사용하는 인덱스를 복합 인덱스라 한다.
아래와 같이 첫번째 필드(userid)는 오름차순으로, 두번째 필드 (score)는 내림차순으로 정렬 해야 하는 상황이 있을때 사용한다.

이미지 출처: https://docs.mongodb.com/manual/core/index-compound/
Compound Indexes — MongoDB Manual
Docs Home → MongoDB ManualMongoDB supports compound indexes, where a single index structure holds references to multiple fields within a collection's documents. The following diagram illustrates an example of a compound index on two fields:Compound index
docs.mongodb.com
Multikey Indexes
필드 타입이 배열인 필드에 인덱스를 적용 할 때는 Multikey 인덱스를 사용한다. 이 인덱스를 통하여 배열에 특정 값이 포함되어 있는 document를 효율적으로 스캔 할 수 있다.
이미지 출처: https://docs.mongodb.com/manual/core/index-multikey/
Multikey Indexes — MongoDB Manual
Docs Home → MongoDB ManualTo index a field that holds an array value, MongoDB creates an index key for each element in the array. These multikey indexes support efficient queries against array fields. Multikey indexes can be constructed over arrays that
docs.mongodb.com
2d Index Internals
지도의 좌표와 같은 데이터를 효율적으로 쿼리하기 위해서 (예: 특정 좌표 반경 x 에 해당되는 데이터를 찾을 때) 사용되는 인덱스.
Text Indexes
텍스트 관련 데이터를 효율적으로 쿼리하기 위한 인덱스.
Hashed Indexes
B-Tree가 아닌 Hash 자료구조를 사용하는 인덱스. Hash는 검색 효율이 B Tree보다 좋지만, 정렬을 하지 않는다.
인덱스 생성: createIndex()
db.collection.createIndex({ KEY: 1 })
- 인덱스를 적용할 필드를 파라미터로 전달.
- 값을 1로 하면 오름차순, -1로 하면 내림차순으로 정렬
1. 단일 필드 인텍스 생성
db.report.createIndex({ score: 1 })
2. 복합 필드 인덱스 생성
db.report.createIndex({ age: 1, score: -1 })
- age를 오름차순으로 정렬한 상태에서 score는 내림차순으로 정렬
인덱스 속성
db.collection.createIndex( { KEY: 1 }, { PROPERTY: true } )
- createIndex() 메소드의 두 번째 인자에 속성값을 document 타입으로 전달
Unique
_id 필드처럼 컬렉션에 단 한 개의 값만 존재할 수 있는 속성
3. email 인덱스에 unique 속성 적용
db.userinfo.createIndex({ email: 1 }, { unique: true })
4. firstName과 lastName 복합인덱스에 unique 속성 적용
db.userinfo.createIndex({ firstName: 1, lastName: 1 }, { unique: true })
partial
document의 조건을 정하여 일부 document에만 인덱스를 적용할 때 사용.
필요한 부분에만 인덱싱을 사용하여 저장공간도 아끼고 속도를 더 높일 수 있다.
5. visitor 값이 1000 보다 높은 document에만 name 필드에 인덱스 적용
db.store.createIndex(
{ name: 1 },
{ partialFilterExpression: { visitors: { $gt: 1000 } } }
)
TTL
Date 타입 혹은 Date 배열 타입의 필드에 적용할 수 있는 속성.
특정시간이 지나면 document를 expire 시켜 컬렉션에서 제거할 수 있다.
6. notifiedDate가 현재시각과 1시간 이상 차이나면 제거
db.notifications.createIndex({ notifiedDate: 1 }, { expireAfterSeconds: 3600 })
참고: https://docs.mongodb.com/manual/core/index-ttl/
TTL Indexes — MongoDB Manual
Docs Home → MongoDB ManualIf you are removing documents to save on storage costs, consider Online Archive in MongoDB Atlas. Online Archive automatically archives infrequently accessed data to fully-managed S3 buckets for cost-effective data tiering.TTL i
docs.mongodb.com
생성된 인덱스 조회: getIndexes()
db.collection.getIndexes()
인덱스 제거: dropIndex()
db.collection.dropIndex()
- 모든 인덱스 (_id 제외)를 제거할 때는 dropIndexes()
✔ Velopert MongoDB 강좌 (https://velopert.com/560) 를 학습한 후 정리한 포스팅 입니다.
'아카이브 > MongoDB' 카테고리의 다른 글
[MongoDB] Document 수정하기 (1) | 2021.12.19 |
---|---|
[MongoDB] find() 메소드 활용 (2) | 2021.12.19 |
[MongoDB] Document 조회하기 (1) | 2021.12.17 |
[MongoDB] Database/ Collection/ Document 생성 및 제거하기 (0) | 2021.12.16 |