ObjectId 총 12바이트이다. 아래와 같이 구성되어 있음
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 타임스탬프 | 장비 | PID | 증가랑 |
db.collection.insert({ 'a': 1 })
db.collection.update({ 'a': 1 }, { '$push': { 'posts': 'abc' } })
$each
사용하면 여러개 값 한 번에 추가 가능. db.collection.update({ 'a': 1 }, { '$push': { 'posts': { '$each': ['a', 'b', 'c'] } } })
$slice
를 결합하여 요소 개수 제한. db.collection.update({ 'a': 1 }, { '$push': { 'top5': { '$each': [ 'a', 'b' ], '$slice': -5 } } })
$ne
사용: db.collection.update({ 'posts': { '$ne': '1' } }, { '$push': { 'posts': '1' }' })
. $addToSet
사용. db.collection.update({}, { '$addToSet': { 'posts': 1 } })
$addToSet
사용: db.collection.update({}, { '$addToSet': { 'posts': { '$each': ['a', 'b', 'c'] } } })
db.collection.remove({ 'a': 1 })
db.collection.drop()
db.collection.update({ 'a': 1 }, { '$pop': { 'posts': -1 } })
.db.collection.update({ 'a': 1 }, { '$pop': { 'posts': 1 } })
.db.collection.update({ 'a': 1 }, { '$pull': { 'posts': 'a' } })
.db.collection.update({ 'a': 1 }, { '$inc': { 'size': 1 } })
db.collection.update({ 'auth': 'lee' }, { '$inc': { 'comments.1.votes': 1 } })
db.collection.update({ 'auth': 'lee' }, { '$set': { 'comments.$.votes': 1 } })
$inc
.info DFM::findAll(): extent a:23C13 was empty, skipping ahead
db.runCommand({ 'collMod': collection, 'usePowerOf2Sizes': ture })
. 콜렉션의 모든 후속 할당을 2^n크기의 블록에 있게 설정db.collection.update({ 'auth': 'lee' }, { '$inc': { 'viewCount': 1 } }, true)
. { 'auth': 'lee', 'viewCount': 1 }
반환db.collection.update({ 'auth': 'lee' }, { '$setOnInsert': { 'createAt': new Date() } })
db.collection.update({ 'auth': 'lee' }, { '$inc': { 'viewCount': 1 } }, false, true)
db.collection.findAndModify({ 'auth': 'lee' }, { '$inc': { 'viewCount': 1 } })
. 이전 viewCount : 24
면 24를 반환하고 실제로 25로 갱신.findAndModify
인자: query
문서를 찾는 조건, sort
결과 정렬, update
찾은 문서 갱신, remove
찾은 문서 삭제 여부 boolean값, new
반환 문서가 갱신하기 전 문서인지 갱신 후 문서인지 설정하는 boolean값, fields
반환 문서 필드 설정. upsert
갱신 입력 여부 boolean값.$in
사용. 여러 키에 대한 or 쿼리는 $or
사용. $nin
은 $in
과 반대 배열 내 조건과 일치하지 않는 문서 반환.$or
보다는 $in
를 사용하라. $or
은 설정된 값의 결과를 병합하는 작업(중복 제거도 포함)이 있기 때문에 $in
를 사용하는 게 효율적이다.$ne
는 비효율적이다. $ne
로 설정된 것 이외의 모든 인덱스를 살펴봐야하기 때문이다.$not
은 대부분 테이블 스캔을 수행한다.$nin
은 항상 테이블 스캔을 수행한다.null
은 자신과 일치하는 것뿐만 아니라 존재하지 않는것도 반환한다.db.collection.find({ 'tags': { $all: [ 'devops', 'network' ] } })
배열에 순서에 상관없이. ‘devops’, ‘network’가 포함된 문서를 반환한다.min()
와 max()
함수를 사용하는 것이 좋음: db.collection.find({ 'a': { '$gt': 1, '$lt': 10 } }).min({ 'a': 1 }).max({ 'a': 10 })
db.collection.find({ 'name.first': 'kh', 'name.last': 'lee' })
. 내장 문서의 키 순서가 바뀌면 db.collection.find({ 'name': { 'first': 'kh', 'last': 'lee' } })
명령어는 아무것도 반환하지 않는다.$where
쿼리는 보안상, 인덱스 사용 불가하기 때문에 사용하지 말아야한다.aggregate
사용
$match
를 가장 앞쪽에 배치하면 불필요한 문서를 먼저 걸러낼 수 있으며, $project
이나 $group
를 사용하기 전에 쿼리가 인덱스를 사용할 수 있다.aggregate
가 메모리 20% 이상을 사용하면 오류가 발생한다.db.collection.ensureIndex({ 'id': 1 })
db.collection.find().sort({ 'id': 1, 'auth': 1 })
는 db.collection.ensureIndex({ 'id': 1, 'auth': 1 })
로 하면 find()
만으로 해결 가능하다.sort()
를 사용 시, 몽고디비는 결과를 반환하기 전 메모리에서 정렬하므로 인덱스를 최대한 활용하는 게 좋다. explain
에서 scanAndOrder: true
가 된다.find()
를 사용할 때, limit()
를 사용하는 것은 효율적이다.db.collection.find({ 'indexing key': 1, query... })
은 처음 index된 키로 범위를 좁히므로 효율적이다.{ 'id': 1 }
로 설정되었을 경우, { 'id': -1 }
로 정렬한다면 몽고 디비가 최적화를 해주기 때문에 { 'id': -1 }
를 index로 설정할 필요가 없다.select
를 모두 포함하고 있다면 퀴리가 커버링된다고 한다. 커버드 쿼리는 explain
에서 indexOnly: true
이다.db.collection.ensureIndex({ 'user.name': 1 })
db.collection.ensureIndex({ 'expireTime': 1 }, { 'expreAfterSeconds': 60*60*24 })
는 24시간 후에 삭제된다.db.collection.ensureIndex({ 'desc': 'text'})
background
옵션을 사용해라. 기본적으로 인덱스를 구축할 때 몽고디비는 데이터베이스의 모든 읽기와 쓰기를 중단한다.