본문 바로가기

개발/db

[mongodb] MongoDB university - M101JS week4 : Indexes

몽고db Index Creation


documents가 디스크에 저장될 때 특정한 순서가 없다.

인덱스가 없는 경우에 쿼리를 하면 콜렉션안의 모든 document를 스캔히야 한다. document가 많으면 작업량이 상당하므로 index를 만드는 것이 좋다.


인덱스 만들기

db.students.createIndex({"student_id": 1, "class_id": -1});


인덱스보기

db.students.getIndexes();


인덱스삭제

db.students.dropIndex({student_id: 1})



Multikey Indexes

db.foo.createIndex({a: 1, b:1});   - a, b가 둘다 배열이면 안 됨(??)

db.foo.explain().find({a:1}); -자세하기보기(사용한 index정보 볼수 있음)


수업에서 나왔던 인덱스는 만드는데 15분 걸림.. 엄청 오래걸릴수 있다(데이터 몇만건.. value가 배열인걸 인덱스로 만들었을때) - 그 동안에 다른 쉘에서도 그 콜렉션에 접근할 수 없다

background: true라는 옵션을 주면 다른 쉘에서 그 콜렉션에 접근할 수 있다. 대신 인덱스 만드는데 더 오래걸림


배열 값은 .(dot)으로 접근하면 됨


type이 exam인데 99.8이 넘는 score을 갖는 document를 찾고 싶다(scores 컬럼의 데이터형식은 type과 score의 object를 갖는 배열임)

1.(O)  db.students.find({'scores': {$elemMatch: {type: 'exam', score: {'$gt': 99.8}}}});

2.(X)   db.students.find({'$and': [{'scores.type': 'exam'}, {'scores.score': '{'$gt': 99.8}'}]})

db.students.explain(). ~"" ~(위 쿼리처럼) --> 이렇게 하면 어떤방식으로 쿼리를 했는지 알 수 있다. 

두번째는 explain으로 내용을 살펴보면(WinningPlan의 inputStage를 분석하면됨)

먼저 scores.score이 99.8이 넘는 것을 찾고 그 다음에 scores.type에 exam이 있는 doc을 찾음..


unique index

db.stuff.createIndex({thing: 1}, {unique: true}) --> 같은 데이터 값이 있으면 유티크 인덱스 못 만듦


sparse Indexes

db.stuff.createIndex({thing: 1}, {unique: true, sparse: true}) --> thing컬럼에 데이터가 없는게 있어도 만들 수 있음


using explain

db.collection.explain().help();

.find() --> wiiningPlan참고.. 


Execution Stat mode

db.example.explain("executionStats").find({a: 1, b: 2});

executionStats에서 중요한 정보 executionTimeMilis, nReturned, inputStage에서 nReturned


db.example.explain("allPlansExecution").find({a: 1, b: 2});

allPlansExcution 참고


covered queries

??????

이해를 못함

몽고디비 문서 http://docs.mongodb.org/manual/core/query-optimization/