db.<collection>.createIndex( { <필드이름(배열)>: <정렬순서> } )
Index Bounds는 몽고 DB가 쿼리를 수행할 때 검색할 인덱스의 범위를 정의함
복합 인덱스(Compound Index: 여러 키값을 갖는 index)에서, 각 인덱스는 배열값을 최대 1개까지만 포함할 수 있음
{ _id: 1, scores_spring: [ 8, 6 ], scores_fall: [ 5, 9 ] }
{ scores_spring: 1, scores_fall: 1 }
{ _id: 1, scores_spring: [8, 6], scores_fall: 9 }
{ _id: 2, scores_spring: 6, scores_fall: [5, 7] }
배열 필드를 통으로 검색하는 쿼리에서는 MongoDB가 맨 앞의 element에 대해서만 index scan에 활용할 수 있고, 통으로 인덱스를 검색할수는 없음
예시)
데이터:db.inventory.insertMany( [ { _id: 5, type: "food", item: "apple", ratings: [ 5, 8, 9 ] } { _id: 6, type: "food", item: "banana", ratings: [ 5, 9 ] } { _id: 7, type: "food", item: "chocolate", ratings: [ 9, 5, 8 ] } { _id: 8, type: "food", item: "fish", ratings: [ 9, 5 ] } { _id: 9, type: "food", item: "grapes", ratings: [ 5, 9, 5 ] } ] )인덱스:
db.inventory.createIndex( { ratings: 1 } )쿼리:
db.inventory.find( { ratings: [ 5, 9 ] } )
- 이 상태에서 위 쿼리는 [5,9]를 한번에 싹 인덱싱 된 상태에서 찾을수가 없음
- 배열의 첫 번째 element인 5에대해서, ratings 배열에 5가 포함된 모든 document를 찾음
- 그다음 결과 중에 ratings 배열이 [5,9]와 완전히 일치하는 document들을 찾아서 반환함
다중 키 인덱스를 이용해서 정렬할 때 Blocking Sort가 발생함.
Multikey Index들은 배열 필드에 대해서 query를 cover 할 수 없음.
db.matches.insertMany( [ { name: "joe", event: ["open", "tournament"] }, { name: "bill", event: ["match", "championship"] } ] )여기에서
db.matches.createIndex( { name: 1, event: 1 } )이렇게 인덱스를 생성했을 때
db.matches.find( { name: "bill" } )이렇게 name 필드에 대한 쿼리는 Cover할 수 있음
-> name 필드가 이 인덱스의 index prefix이니까
근데 name이랑 event 둘다 쿼리에 포함된 경우 Cover할 수가 없음
참고: