본문 바로가기

IT/Design Data

[NoSQL] Mongo DB 데이터타입 및 인덱스


데이터

 

MongoDB에서는 하나의 Document 저장 시 3가지 메서드 사용

1. INSERT() : Collection에 하나의 Document 최초 저장

2. UPDATE() : 하나의 Collection에서 특정 필드만 수정할 때 사용(필드 단위로 변경)

3. SAVE() : 하나의 Document에서 특정 필드만 변경하더라도, Document 단위로 데이터를 변경

 

 

JSON 타입과 BSON 타입

자바스크립트 형식의 오브젝트 표기법

; Javascript Obect Notation

ex) p = {

eno : 1

,job : "developer"

,company : "xx"

}

 

db.insert(p)

 

BSON ; Binary Serial Object Notation)

 데이터 베이스 내에 저장될때 BSON 데이터로 변환되어 저장

 

데이터 타입

null형
{ "name" : null }

undefined형 { "name" : undefined }
boolean형 { "name" : true }
64비트 부동소숫점 { "age" : 21 }
string형 { "name" : "neo" }
objectId형 { "oid" : ObjectId() }
date형 { "regdate" : new Date() }
정규식형 { "name" : /neo/i }
javascript형 { "func" : function() { /- ... *- } }
array형 { "array" : [ 1, 2, 3 ] }
문서형 { "person" : { "name" : "neo" } }


Read
> db.person.findOne()
처음 문서 하나를 조회
 
> db.person.find()
저장된 문서의 전체를 조회


Update
> person1.desc = []
> db.person.update({ name : "neo" }, person1)
 
> var person2 = db.person.findOne({"name" : "neo"});
> person2.desc = {"blood", "B"}

Delete
> db.person.remove({ name : "neo" })
컬렉션 내에 이름이 neo인 문서를 삭제
 
> db.person.remove()
모든 컬렉션의 문서를 삭제


몽고디비에서 인덱스를 만들고 사용하는 간단한 방법

 

 인덱스 만들기 

  - <collection>.ensureIndex({key:1 or -1})   예) db.things.ensureIndex({age:1});

  - 1 (양수) : ascending,  -1 (음수) : descending

> use indextest
switched to db indextest
> db.things.save({age:12, name:'dowon', title:'hi'});
> db.things.save({age:22, name:'dowon2', title:'hi2'});
> db.things.ensureIndex({age:1});
> db.system.indexes.find();
{ "v" : 1, "key" : { "_id" : 1 }, "ns" : "indextest.things", "name" : "_id_" }
{ "v" : 1, "key" : { "age" : 1 }, "ns" : "indextest.things", "name" : "age_1" }

 

 

인덱스 삭제하기 

  - <collection>.dropIndexes({key:1 or -1})  예) db.things.dropIndexes({age:1});

> db.things.dropIndexes({age:1});
{
    "nIndexesWas" : 3,
    "msg" : "non-_id indexes dropped for collection",
    "ok" : 1
}
> db.system.indexes.find();
{ "v" : 1, "key" : { "_id" : 1 }, "ns" : "indextest.things", "name" : "_id_" }

 

 

인덱스 종류

  - 복합 인덱스 (Compound Key Index) : 여러개의 key를 기반으로 인데스 생성가능 

     예) db.things.ensureIndex({age:1, name:-1});

  - 희소 인덱스 (Sparse Index) : 색인된 필드만 인덱스 한다 

     예) db.things.ensureIndex({title:1}, {sparse:true}); 기본은 false

  - Unique 인덱스 : 색인된 키에 대해 이미 있거나 중복된 것은 insert되지 않는다 

     예) db.things.ensureIndex({name:1}, {unique: true});