반응형

Document를 집계하는 방법

    1. DB의 모든 정보를 불러와 Application 단계에서 집계하는 방법
      • 네트워크 프로토콜을 통해MongoDB 외부로 정보를 넘겨야 하기 때문에 모든 Document로 인해 메모리 적재 + 네트워크 비용 발생
    2. MongoDB의 맵-리듀스 기능 이용
      • Java Script 엔진과 정보 교환을 위해 메모리 사용 (BSON to Javascript로 변환)
        • 사용자 쿼리에 대한 결과 필드를 가져와, 별도의 Thread에서 JavaScript를 실행(Aggregation도 비슷하지만, JS Thread가 아닌 C++로 실행되어 훨씬 빠름)
      • JSMode라는 설정을 사용하면 속도는 빨라지지만, 대량의 메모리가 필요
        • JSMode : false
          • Javascript 엔진에서 다시 MongoDB내부로 정보를 보내는 과정이 추가
        • JSMode : true
          • Javascript 엔진 내에서 Document를 grouping 하는 작업을 수행
      • Reduce 작업
        • 그룹핑된 Document 내에서 연산을 진행
          • JS Engine에서 수행
      • 자유도가 높아, MongoDB 내부에서 아직 유지중
      • 단, 다양한 집계 파이프라인의 명령어가 추가되면서 맵-리듀스 방식보다 더 많이 사용(Aggregation을 사용 못하는 경우 사용)

  1. MongoDB의 집계 파이프라인 기능을 이용
    • Document를 순차적으로 받아서 집계 처리를 MongoDB 내부에서 진행(적은 메모리로 빠른 속도 성능)
      • 순차적으로 받아서 처리하면 정확한 데이터가 맞을지..?
      • 전부 받아 오는 것은 동일한데,  메모리에 모두 올려서 처리할 것인지, 하나씩 받아서 처리하는 것의 차이?

 

Application

Map-Reduce

Pipeline

비고

자유도

좋다

좋다

나쁘다

 

처리 속도

가장 나쁘다.

보통

가장 좋다

pipeline 이 map-reduce 보다 10배 더 빠름

램 사용량

매우 높음

높음

낮음

 

처리 위치

App. 내부

자바스크립트 엔진

MongoDB 내부

 

참고 : https://stackoverflow.com/questions/32131828/mongo-map-reduce-or-aggregate-strategy

https://stackoverflow.com/questions/13908438/is-mongodb-aggregation-framework-faster-than-map-reduce

Aggreration 이란?

  • 여러 Document 들을 grouping하여 계산하여, 단일 결과를 반환
  • Aggregation, Map-reduce, 단일 목적 Aggregation이 존재
  • 처리 단계의 출력이 다음 단계의 입력으로 이어지는 형태로 연결된 구조 (linked list)
    • 누적으로 계산하는 형태

 

  • 주요 파이프라인
    • 출처 : "맛있는 MongoDB"
git clone https://github.com/Karoid/mongodb_tutorials.git
cd mongodb_tutorials/operating_expenses/

mongoimport -d operatin_expenses -c population --file population.json
mongoimport -d operatin_expenses -c city_or_province --file city_or_province.json
mongoimport -d operatin_expenses -c operating_expenses -c local --file local.json

 

Stage

설명

형식

$project

어떤 필드를 숨기고, 어떤 필드를 새로 만들지 정하는 역할

{$project:{필드 : bollean}}

{$project:{필드 : expression}}

$group

_id 값으로 지정된 내용이 같은 Document끼리 그룹화

{$group: {_id:expression, field1:{accumulator1:expression1},...}}

$match

Document를 필터링해서 반환. find문과 비슷한 역할

{$match:{쿼리}}

$unwind

입력 Document에서 배열 필드를 분해하여 각 요소에 대한 Document로 분리하여 출력

{$unwind:필드경로}

{

  $unwind :

   {

      path:필드경로,

      includeArrayIndex:문자,

      preserveNullAndEmptyArrays: bollean

   }

}

$out

파이프라인의 결과를 Collection에 기록

{ $out: "컬렉션명"}

 

$group

연산자

설명

예시

$first

그룹의 첫 번째 값을 반환.

$sort 를 해야 의미가 있음

{

  $group : { _id:"$그룹대상", 원하는필드명:{$first:"$값필드"} }

}

 

(max와 동일하다고 생각했지만 결과 값이 살짝 다름)

 

db.population.aggregate({$group:{_id:"$city_or_province",population:{$first:"$population"}}})

$last

그룹의 마지막 값을 반환.

$sort 를 해야 의미가 있음

{

  $group : { _id:"$그룹대상", 원하는필드명:{$last:"$값필드"} }

}

 

(min와 동일하다고 생각했지만 결과 값이 살짝 다름)

db.population.aggregate({$group:{_id:"$city_or_province",population:{$last:"$population"}}})

$max

그룹에서 해당 필드의 최대 값을 반환

{

  $group : { _id:"$그룹대상", 원하는필드명:{$max:"$값필드"} }

}

db.population.aggregate({$group:{_id:"$city_or_province",population:{$max:"$population"}}})

$min

그룹에서 해당 필드의 최소 값을 반환

{

  $group : { _id:"$그룹대상", 원하는필드명:{$min:"$값필드"} }

}

db.population.aggregate({$group:{_id:"$city_or_province",population:{$min:"$population"}}})

$avg

그룹에서 해당 필드의 평균 값을 반환

{

  $group : { _id:"$그룹대상", 원하는필드명:{$avg:"$값필드"} }

}

$sum

그룹에서 해당 필드의 합산 값을 반환

{

  $group : { _id:"$그룹대상", 원하는필드명:{$sum:"$값필드"} }

}

 

db.population.aggregate({$group:{_id:"$city_or_province",population:{$sum:"$population"}}})

$push

그룹에서 해당 필드의 모든 값을 배열에 넣어 반환.

중복을 제거하지 않음

{

  $group : { _id:"$그룹대상", 원하는필드명:{$push:"$값필드"} }

}

 

db.population.aggregate({$group:{_id:"$city_or_province",population:{$push:"$population"}}})

$addToSet

그룹에서 해당 필드의 모든 값을 배열에 넣어 반환.

반환하는 배열에 중복된 요소가 없음

{

  $group : { _id:"$그룹대상", 원하는필드명:{$addToSet:"$값필드"} }

}

 

db.population.aggregate({$group:{_id:"$city_or_province",population:{$addToSet:"$population"}}})

  • 샘플 데이터

$match

  • find 명령어와 비슷
#rating 이 4보다 크거나 같은 내역, id들을 배열의 형태로 정리하도록 명령($push)

> db.rating.aggregate([
{$match: {rating: {$gte:4}}}
, {$group: {_id: "$rating", user_ids:{$push:"$user_id"}}}
])

 

$unwind

  • 하나의 Document에 들어있는 배열 요소들을 각각의 Document에 하나의 값으로 갖도록 만드는 작업
반응형
반응형

샘플 데이터

  • "맛있는 MongoDB"
    • 샘플 데이터 공유
$ git clone https://github.com/Karoid/mongodb_tutorials.git
$ ec2-user@mongodb:~$ cd mongodb_tutorials/car_accident/

ec2-user@mongodb:~/mongodb_tutorials/car_accident$ mongoimport -d car_accident -c area --file area.json
2021-03-02T13:29:00.380+0000    connected to: localhost
2021-03-02T13:29:00.403+0000    imported 228 documents
ec2-user@mongodb:~/mongodb_tutorials/car_accident$
ec2-user@mongodb:~/mongodb_tutorials/car_accident$ mongoimport -d car_accident -c by_month --file by_month.json
2021-03-02T13:29:32.252+0000    connected to: localhost
2021-03-02T13:29:32.309+0000    imported 227 documents
ec2-user@mongodb:~/mongodb_tutorials/car_accident$
ec2-user@mongodb:~/mongodb_tutorials/car_accident$ mongoimport -d car_accident -c by_road_type --file by_road_type.json
2021-03-02T13:29:50.266+0000    connected to: localhost
2021-03-02T13:29:50.309+0000    imported 227 documents
ec2-user@mongodb:~/mongodb_tutorials/car_accident$
ec2-user@mongodb:~/mongodb_tutorials/car_accident$ mongoimport -d car_accident -c by_type --file by_type.json
2021-03-02T13:30:08.372+0000    connected to: localhost
2021-03-02T13:30:08.408+0000    imported 687 documents

> show dbs
admin        0.000GB
car_accident  0.000GB
config        0.000GB
local        0.000GB
test          0.000GB
>
> use car_accident
switched to db car_accident
> show tables
area
by_month
by_road_type
by_type

 

  • Find 관련 명령어에는 여러 개가 있으며, 그 중에 많이 사용하는 위주로 가이드 하며, 필요 시 추가 가이드 진행 예정

명령어

내역

find()

검색

findAndModify()

검색 후 수정

Update, upset, remove 모두 가능

new : true를 설정하여 update 이후 값을 리턴

new : false 또는 미적용 시 update 이전 값을 리턴

 

db.monsters.findAndModify({

    query: { name: "Dragon" },

    update: { $inc: { att: 1000 } ,$set :{"name":"Dragon","hp":4000,"att":1000}},

    upsert: true,

    new : true

})

findOne()

한건만 검색

findOneAndDelete()

한건만 검색 후 삭제

findOneAndReplace() > v3.2

한건만 검색 후 변경

returnNewDocument : true 설정하여 변경 전후 확인 가능

Replace 와 Update의 경우 Update는 명시한 필드만 변경 되지만, Replace의 경우는 명시한 필드 변경 외에는 나머지 필드는 모두 삭제 됨

가급적이면 Update만 사용 해야함

findOneAndUpdate()  > v3.2

한건만 검색 후 변경

returnNewDocument : true 설정하여 변경 전후 확인 가능

 

[Find]

  • Find명령어 사용 시 필요한 filed 명을 사용하여 검색하시기 바랍니다.(Covered Query)
  • Ex) db.bios.find( {조건}, {_id:0, name:1 , money:1})
    • 쿼리가 요구하는(리턴되는) 내용의 모든 필드가 하나의 Index에 포함되어 있으므로, Index만 조회하기 때문에 Document를 조회하는 것보다 훨씬 빠름(일반적으로 인덱스 키는 RAM에 적재되 있거나 디스크에 순차적으로 위치 하기 때문)
    • _id 필드를 0으로 명시하지 않는 경우, 결과 값에서 표현이 되기 때문에, covered query 조건이 되지 않으므로, 반드시 _id 필드를 0으로  명시
    • 쿼리에 필드가 없거나 필드의 값이 null 이 되면 안된다. i.e. {"field" : null} or {"field" : {$eq : null}}
    • v3.6 부터 embedded document의 경우도 적용 (이전 버전 에서는 불가능?)
      • db.userdata.find( { "user.login": "tester" }, { "user.login": 1, _id: 0 } )
      • 테스트 결과 안되요ㅠ(알고 계신 분 알려주세요)
    • 제한
      • Geospatial Index 에서는 사용 못함
      • Multikey Index에서 배열 필드에 대해서는 Covered index 가 불가능(v3.6부터 non-array field들에 대해서는 사용 가능)
    • Covered Query
  • field 명시 방법
    • 필드에 _id 여부는 항상 명시해야 함(_id를 쿼리 결과 내에서 표현하거나 표현하지 않는 것에 대해 명시를 반드시 해야 함)
    • _id에 대해서만 혼용 사용 가능하며, 다른 필드들에 대해서는 보여 주고 싶은 것에 대해서만 1로 명시, 0으로 명시하면 에러 발생
    • Ex ) > db.thing.find( { }, {_id:0, empno: 1} )  // empno만 표시하고, _id 및 다른 필드는 표시 안함. // 여기서 중요한건 _id는 항상 명시해 줘야 하며, 보고 싶은 필드만 1로 설정해서 표시 // 다른 필드의 경우 birth 필드가 있더라도 birth:0 으로 하면 에러 발생...왜???모르겠음
    • 만약 empno만 빼고 다 보고자 하면 그때는 > db.thing.find( { }, {empno: 0} ) 이런 식으로 표시
    • 보고 싶은 field가 있다면, field를 명시할 때 보겠다는 field 들만 명시를 하고,field 명시 여부를 혼용해서 명시하게 되면, 에러가 발생
    • 반대로 보고 싶지 않은 field가 있다면 명시 안하겠다는 field 들만 명시를 해야 함

[Filed] 

  • Covered Query Test
# semester 에 대한 Index 확인
> db.employee.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_"
        },
        {
                "v" : 2,
                "key" : {
                        "semester" : 1
                },
                "name" : "semester_1"
        }
]

# _id 필드를 명시적으로 0 처리 하지 않으면, 자연스럽게 _id 필드도 같이 표시되기 때문에 명시적으로 _id 필드를 표시 안한다고 해야, Convered query 적용 여부를 확인 가능
> db.employee.find({semester:3},{_id:0, semester:1}).explain()

# 필드를 표시 안하게 되는 경우 _id 필드가 표현 되기에 covered query가 되지 않음
> db.employee.find({semester:3},{"field" : null}).explain()

#  covered index 확인

# 필드를 표시 안 하게 되는 경우 _id 필드가 표현 되기에 covered query가 되지 않음 (단순 인덱스 스캔 - fetch 진행)

#실패 - embedded Document 에 대한 covered query 실패
> db.inventory.insertMany( [
    { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
    { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
    { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
    { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
    { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("603cf504850313ab26e27ced"),
                ObjectId("603cf504850313ab26e27cee"),
                ObjectId("603cf504850313ab26e27cef"),
                ObjectId("603cf504850313ab26e27cf0"),
                ObjectId("603cf504850313ab26e27cf1")
        ]
}
>
> db.inventory.createIndex({item:1, "instock.qty":1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
# 데이터 확인
> db.inventory.find({item:"journal", "instock.qty":5}, {_id:0,item:1, "instock.qty":1})
{ "item" : "journal", "instock" : [ { "qty" : 5 }, { "qty" : 15 } ] }

# covered 체크
> db.inventory.find({item:"journal", "instock.qty":5}, {_id:0,item:1, "instock.qty":1}).explain()

# 단일로 진행 실패
> db.inventory.insertOne({ item: "test_item", instock: [{warehouse: "A", qty: 5}]})
> db.inventory.find({item:"test_item", "instock.qty":5}, {_id:0,item:1, "instock.qty":1}).explain()

# 단일로 진행 실패 2
> db.inventory.insertOne({ item: "test_item_2", instock: [{qty: 5}]})
> db.inventory.find({item:"test_item_2", "instock.qty":5}, {_id:0,item:1, "instock.qty":1}).explain()

비교(Comparison) 연산자

operator

설명

 

$eq

(equals) 주어진 값과 일치하는 값

find({ 대상필드:{원하는연산자:조건값}})

 

 

 

 

 

$gt

(greater than) 주어진 값보다 큰 값

$gte

(greather than or equals) 주어진 값보다 크거나 같은 값

$lt

(less than) 주어진 값보다 작은 값

$lte

(less than or equals) 주어진 값보다 작거나 같은 값

$ne

(not equal) 주어진 값과 일치하지 않는 값

$in

주어진 배열 안에 속하는 값

반드시 배열 형태로 질의

find({필드:{$in / $nin :[ { 원하는값 A } , { 원하는값 B } ] } })

$nin

주어진 배열 안에 속하지 않는 값

논리 연산자

operator

설명

 

$or

주어진 조건중 하나라도 true 일 때 true

배열 형태로 질의 진행

find({$or / $and / $not / $nor : [{조건A},{조건B}]})

$and

주어진 모든 조건이 true 일 때 true

$not

주어진 조건이 false 일 때 true

$nor

주어진 모든 조건이 false 일때 true

> db.inventory.find({"instock.qty":{$eq:5}})
{ "_id" : ObjectId("603cf504850313ab26e27ced"), "item" : "journal", "instock" : [ { "warehouse" : "A", "qty" : 5 }, { "warehouse" : "C", "qty" : 15 } ] }
{ "_id" : ObjectId("603cf504850313ab26e27cee"), "item" : "notebook", "instock" : [ { "warehouse" : "C", "qty" : 5 } ] }
{ "_id" : ObjectId("603cf504850313ab26e27cf0"), "item" : "planner", "instock" : [ { "warehouse" : "A", "qty" : 40 }, { "warehouse" : "B", "qty" : 5 } ] }
{ "_id" : ObjectId("603cf675850313ab26e27cf2"), "item" : "test_item", "instock" : [ { "warehouse" : "A", "qty" : 5 } ] }
{ "_id" : ObjectId("603cf6d7850313ab26e27cf3"), "item" : "test_item_2", "instock" : [ { "qty" : 5 } ] }

# county 가 종로구,중구 또는 population 이 3,552,490 보다 큰 경우
> db.area.find({$or:[{county: "종로구"},{county:"중구"},{population:{$gte:3552490}}]})

{ "_id" : ObjectId("5c88f9f70da47a8507752775"), "city_or_province" : "서울", "county" : "종로구", "population" : 152737 }
{ "_id" : ObjectId("5c88f9f70da47a8507752776"), "city_or_province" : "서울", "county" : "중구", "population" : 125249 }
{ "_id" : ObjectId("5c88f9f70da47a850775278e"), "city_or_province" : "부산", "county" : "중구", "population" : 45208 }
{ "_id" : ObjectId("5c88f9f70da47a8507752830"), "city_or_province" : "대구", "county" : "중구", "population" : 79712 }
{ "_id" : ObjectId("5c88f9f70da47a850775283f"), "city_or_province" : "인천", "county" : "중구", "population" : 115249 }
{ "_id" : ObjectId("5c88f9f70da47a8507752848"), "city_or_province" : "대전", "county" : "중구", "population" : 252490 }
{ "_id" : ObjectId("5c88f9f70da47a850775284c"), "city_or_province" : "울산", "county" : "중구", "population" : 242536 }

# county 가 종로구,중구 가운데, population 이 125,249 보다 큰 경우 (and / or 연산이 공존)
> db.area.find({$and:[{$or:[{county: "종로구"},{county:"중구"}]},{population:{$gte:125249}}] })

{ "_id" : ObjectId("5c88f9f70da47a8507752775"), "city_or_province" : "서울", "county" : "종로구", "population" : 152737 }
{ "_id" : ObjectId("5c88f9f70da47a8507752776"), "city_or_province" : "서울", "county" : "중구", "population" : 125249 }
{ "_id" : ObjectId("5c88f9f70da47a8507752848"), "city_or_province" : "대전", "county" : "중구", "population" : 252490 }
{ "_id" : ObjectId("5c88f9f70da47a850775284c"), "city_or_province" : "울산", "county" : "중구", "population" : 242536 }

# county 가 종로구,중구 가운데, population 이 125,249 보다 큰 경우 ($and / $in 연산이 공존)
> db.area.find({$and:[{county:{$in:["종로구","중구"]}}, {population:{$gte:125249}}] })

{ "_id" : ObjectId("5c88f9f70da47a8507752775"), "city_or_province" : "서울", "county" : "종로구", "population" : 152737 }
{ "_id" : ObjectId("5c88f9f70da47a8507752776"), "city_or_province" : "서울", "county" : "중구", "population" : 125249 }
{ "_id" : ObjectId("5c88f9f70da47a8507752848"), "city_or_province" : "대전", "county" : "중구", "population" : 252490 }
{ "_id" : ObjectId("5c88f9f70da47a850775284c"), "city_or_province" : "울산", "county" : "중구", "population" : 242536 }

$regex 연산자

  • $regex 연산자(정규표현식)를 이용하여, Document를  찾을 수 있음
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
{ <field>: /pattern/<options> }
  • 4번쨰 라인 처럼 $regex 를 작성하지 않고 바로 정규식을 쓸 수도 있으며,  $options 정보 를 이용도 가능

option

설명

i

대소문자 무시

m

정규식에서 anchor(^) 를 사용 할 때 값에 \n 이 있다면 무력화

x

정규식 안에있는 whitespace를 모두 무시

s

dot (.) 사용 할 떄 \n 을 포함해서 매치

  • 정규식 test_item_[1-2] 에 일치하는 값이 item 조회
    • 조회하는 데이터의 "" 사용 안함.
> db.inventory.find({item : /test_item_[1-2]/})
{ "_id" : ObjectId("603cf6d7850313ab26e27cf3"), "item" : "test_item_2", "instock" : [ { "qty" : 5 } ] }

#대소문자 무시 i 옵션 이용
> db.inventory.find({item : /Test_item_[1-2]/i})
{ "_id" : ObjectId("603cf6d7850313ab26e27cf3"), "item" : "test_item_2", "instock" : [ { "qty" : 5 } ] }

$text 연산자

  • Text 검색으로 단어 형태만 검색이 가능 (띄어쓰기 단위 -> 가령 한 단어 내에 포함된 것은 검색이 안됨)
  • 대 소문자 구분 안함
  • 각 나라별 언어에 맞춰 검색이 지원되고 있지만, 한글은 지원되지 않음.
  • 문자열 인덱스를 만들어야 사용 가능
    • 해당 Collection 의 텍스트 인덱스 안에서만 작동하기 때문

필드

설명

$search

검색하려는 내용을 담는다. 구절로 설정되지 않으면 띄어 쓴 단어를 포함한 모든 Document반환

$language

Option. 검색하는 언어를 설정

MongoDB가 지원하는 언어를 설정할 수 있으며, 설정되지 않으면 인덱스에 설정된 내용을 따름

$caseSensitive

Option. Bollean 값.

문자의 대,소문자 구분을 결정하며, Default는 구분하지 않음(False)

$diacriticSensitive

Option. Bollean 값.

e`와 e 와 같이 알파벳의 위아래에 붙이는 기호를 무시할지를 정함. Default로는 false (무시 하지 않음)

> db.inventory.createIndex({ item:"text" })

> db.inventory.find( {$text:{$search:"test"}} )
{ "_id" : ObjectId("603e498748883f8cbbc18bd9"), "item" : "keep Test" }
{ "_id" : ObjectId("603e47f148883f8cbbc18bd7"), "item" : "keep test" }
{ "_id" : ObjectId("603e47e248883f8cbbc18bd6"), "item" : "test keep" }

  • 문자열 내 test 를 검색하는데, test_item 같은 것은 검색이 안됨. keep test / test keep 같이 띄어쓰기 된 것에 대해서만 검색

$where 연산자

  • $where 연산자를 통하여 javascript expression 을 사용 가능
#comments field 가 비어있는 Document 조회

> db.articles.find( { $where: "this.comments.length == 0" } )
{ "_id" : ObjectId("56c0ab6c639be5292edab0c4"), "title" : "article01", "content" : "content01", "writer" : "Velopert", "likes" : 0, "comments" : [ ]

 

$elemMatch 연산자

  • $elemMatch 연산자는 Embedded Documents 배열을 쿼리할때 사용
# comments 중 "Charlie" 가 작성한 덧글이 있는 Document 조회를 했을때, 게시물 제목과 Charlie의 덧글부분만 읽고싶은 경우
# 이렇게 해보면 의도와는 다르게  Delta 의 덧글도 출력
> db.articles.find(
    {
        "comments": {
            $elemMatch: { "name": "Charlie" }
        }
    },
    {
        "title": true,
        "comments.name": true,
        "comments.message": true
    }
)
{
        "_id" : ObjectId("56c0ab6c639be5292edab0c6"),
        "title" : "article03",
        "comments" : [
                {
                        "name" : "Charlie",
                        "message" : "Hey Man!"
                },
                {
                        "name" : "Delta",
                        "message" : "Hey Man!"
                }
        ]
}

 

  • Embedded Document 배열이 아니라 아래 Document의 "name" 처럼 한개의 Embedded Document 경우
> db.users.find({
    "username": "velopert",
    "name": { "first": "M.J.", "last": "K."},
    "language": ["korean", "english", "chinese"]
  }
)
> db.users.find({ "name.first": "M.J."})
  • Document의 배열이아니라 그냥 배열일 시에는 다음과 같이 Query
> db.users.find({ "language": "korean"})

projection

  • find() 메소드의 두번째 parameter 인 projection
  • 쿼리의 결과값에서 보여질 field를 정할 대 사용
# article의 title과 content 만 조회

> db.articles.find( { } , { "_id": false, "title": true, "content": true } )
{ "title" : "article01", "content" : "content01" }
{ "title" : "article02", "content" : "content02" }
{ "title" : "article03", "content" : "content03" }

$slice 연산자

  • projector 연산자 중 $slice 연산자는 Embedded Document 배열을 읽을때 limit 설정
# title 값이 article03 인 Document 에서 덧글은 하나만 보이게 출력
$slice 가 없었더라면, 2개를 읽어와야하지만 1개로 제한을 두었기에 한개만 출력

> db.articles.find({"title": "article03"}, {comments: {$slice: 1}}).pretty()
{
        "_id" : ObjectId("56c0ab6c639be5292edab0c6"),
        "title" : "article03",
        "content" : "content03",
        "writer" : "Bravo",
        "likes" : 40,
        "comments" : [
                {
                        "name" : "Charlie",
                        "message" : "Hey Man!"
                }
        ]
}

 

 

$elemMatch

  • 위의 elemMatch 는 조건 연산자에서 사용하는 것이며,
  • 해당 elemMatch 는 필드 내, 즉 projection 파라메터 입니다.
# $elemMatch 연산자를 projection 연산자로 사용하면 이를 구현 가능
# comments 중 "Charlie" 가 작성한 덧글이 있는 Document 중 제목, 그리고 Charlie의 덧글만 조회 (필드 선언 시 다시 한번 더 eleMatch를 진행하게 되면 Delta 의 댓글은 안보임
> db.articles.find(
...     {
...         "comments": {
...             $elemMatch: { "name": "Charlie" }
...         }
...     },
...     {
...         "title": true,
...         "comments": {
...             $elemMatch: { "name": "Charlie" }
...         },
...         "comments.name": true,
...         "comments.message": true
...     }
... )
{ "_id" : ObjectId("56c0ab6c639be5292edab0c6"), "title" : "article03", "comments" : [ { "name" : "Charlie", "message" : "Hey Man!" } ] }

 

[findAndModify]

  • Single Document 에 대한 수정하고 반환
  • 반환 된 Document는 수정에 대한 결과가 아님
  • 반환 된 Document 에 수정한 내역을 확인하고 싶으면 new Option을 이용
    • new 옵션을 true로 하는 경우 변경 후의 결과 값을 보여주며, Default 로 new 옵션을(false) 선언하지 않는 경우 변경 되기 전 값을 출력
# mosters 에서 name이 'Demon' 의 att를 350으로 변경하고 변경한 후 결과 확인
> db.monsters.findAndModify({ query: { name: 'Demon' }, update: { $set: { att: 350 } }, new: true })

db.collection.findAndModify({
    query: <document>,
    sort: <document>,
    remove: <boolean>,
    update: <document or aggregation pipeline>, // Changed in MongoDB 4.2
    new: <boolean>,
    fields: <document>,
    upsert: <boolean>,
    bypassDocumentValidation: <boolean>,
    writeConcern: <document>,
    collation: <document>,
    arrayFilters: [ <filterdocument1>, ... ]
});

> db.monsters.findAndModify({
    query: { name: "Dragon" },
    update: { $inc: { "att": 1000 } ,$set :{"name":"Dragon","hp":4000,"att":1000}},
    upsert: true,
    new : true
})

> db.monsters.findAndModify({
    query: { name: "Dragon" },
    update: {$set :{"hp":2000,"att":2000}},
    upsert: true,
    new : true
})

> db.monsters.findAndModify({
    query: { name: "Dragon" },
    update: {$set :{"hp":3000,"att":2000}},
    upsert: true
})

# upsert / new
> db.monsters.find( {query:{ name: "Dragon_Baby" }} )
> db.monsters.findAndModify({
    query: { name: "Dragon_Baby" },
    update: {$set :{"hp":1000,"att":500}},
    upsert: true,
    new : true
})

# remove
> db.monsters.findAndModify({
    query: { name: "Dragon_Baby" },
    remove: true
})

# 여러개일 경우
> db.monsters.findAndModify({
    query: { name: "Dragon" },
    update: {$set :{"hp":4000,"att":5000}},
    upsert: true
})
  • new Option : true

  • upsert: true / new : true

  • remove : true
    • new:true
      • return 이 없기 때문에 에러
    • update : {xxxx}
      • 당연히 remove 되는데 update 에러 진행
    • remove 가 정상적으로 진행 시
      • 진행 이전 데이터 return  후 삭제

 

  • 여러 개일 경우
    • 역시 한 건만 변경 (update 처럼)

참고 : https://velopert.com/479

 

 

Cursor

 

반응형
반응형

기본 데이터 처리

  • ObjectID

    • 다만 cluster index는 아니며, mongodb 에는 모든 Index 가 Non-cluster Index
    • 아래와 같은 방식으로 생성 되기 때문에 Client에서 생성하여 제공?
    • 앞에 4byte는 유닉스 시간
    • 다음 3byte는 기기의 id 값
    • 다음 2byte는 프로세스 id 값
    • 마지막 3byte는 랜덤 값부터 시작하는 카운터로 구성
    • Document Insert 진행 시 _id 를 명시적으로 생성하지 않으면, "_id" 필드가 ObjectID 타입으로 자동 생성
    • _id 는 서로 겹치지 않는 ObjectID 타입으로 값을 할당 PK라고 생각하면 가능
    • 동시에 생성되어도 서로 다른 값이 생성되어 유일 값(unique)
    • ObjectID 값은 "유닉스시간+기기id+프로세스id+카운터" 로 구성
    • ObjectId.getTimestamp() 하면 생성된 시점을 알아낼 수 있음. (ObjectID를 이용하면 시간 range 로 검색이 가능)
> ObjectId("60371e375adcd7d623c78b3d").getTimestamp()
ISODate("2021-02-25T03:49:11Z")

> ObjectId("60371e8d5adcd7d623c78b3e").toString()
ObjectId("60371e8d5adcd7d623c78b3e")

> ObjectId("60371e8d5adcd7d623c78b3e").valueOf()
60371e8d5adcd7d623c78b3e

  • UUID

    • 출처 : charsyam-[입 개발] Global Unique Object ID 생성 방법에 대한 정리
    • Universally unique identifier 의 약어로, 16-octet(128bit) 크기의 32개의 Hexa로 표시
    • OSF에서 표준화(개방 소프트웨어 재단(Open Software Foundation)-유닉스 운영 체제의 일부로 오픈 표준을 만들 목적으로 1984년의 미국 National Cooperative Research and Production Act 하에 1988년에 설립된 비영리 단체)
    • UUID를 구현하는데는 다양한 방식이 있는데, MAC address 나 HASH(md5, sha-1) 등을 이용한 방식이 유명
    • MAC address 자체가 unique 하기 때문에, 여기에 현재의 시간을 붙이는 방식으로 구현이 가능

 

 

  • runCommand

    • Tool 에서 많이 보았던 command
    • 지정한 DB에서 도우미 제공해 주는 명령어
    • runCommand 를 사용하면, 내부 형태만 잡아 준다면 쉽게 접근이 가능
# 일반적으로 사용하는 명령어는 command 에 작성하여 사용 가능
# Default
> db.runCommand(
  {
	  명령어
  }
)

# 관리 administrative 명령어의 경우 아래와 같이 사용 가능
> db.adminCommand( { <command> } )

 

      • insert

> db.runCommand(
  {
    insert: <collection>,
    documents: [ <document>, <document>, <document>, ... ], // insert 할 내역을 array 형태로 작성
    ordered: <boolean>, // default : true (batch Insert 중 하나라도 실패하면 모든 명령어 실패 / false : Batch Insert 중 하나가 실패하더라도 다음 insert 진행)
    writeConcern: { <write concern> }, // write concern 으로 Transaction 처리하는 경우 명시적으로 설정 하지 말것. - Default 권장
    bypassDocumentValidation: <boolean>, // 유효성 검사로 Enable 하는 경우 유효성 검사를 생략
    comment: // Comment 작성으로 작성하게 되면 mongod log message 에 attr.command.cursor.comment 필드에 작성. (v4.4) -> 찾지 못했습니다. db.adminCommand( { getLog: } ) 참고 : https://docs.mongodb.com/manual/reference/command/getLog/#dbcmd.getLog 참고2 : https://docs.mongodb.com/manual/reference/log-messages/#log-messages-ref
  }
)

# insert Sample
> db.runCommand(
	{
      insert : 'employee'
      , documents:
      [
          {name : 'Hyungi.Kim'
          , Pos : ['dba','devops','develope']
          , wanted:['job','money']
          }
      ]
	}
)

# comment
> db.runCommand(
	{
		insert : 'employee'
		, documents:
		[
          {name : 'Hyungi'
          , Pos : ['dba','devops','develope']
          , wanted:['job','money']
          , memo : 'Add Comment'
          }
		]
	, comment : 'Comment Write by Hyungi.Kim'
	}
)

# inserMany
> db.runCommand(
  {
    insert : 'employee'
    , documents:
    [
      {name : 'Louis'
      , Pos : ['DB Engineer']
      , wanted:['dba']
      } ,
      {name : 'Bong'
      , Pos : ['Student']
      , wanted:['Soccer Player']
      }
    ]
  }
)

> db.runCommand(
  {
  insert : 'students'
  , documents:
    [
      { "_id" : 7, semester: 3, "grades" : [ { grade: 80, mean: 75, std: 8 },
        { grade: 85, mean: 90, std: 5 },
        { grade: 90, mean: 85, std: 3 } ] }
        ,
        { "_id" : 8, semester: 3, "grades" : [ { grade: 92, mean: 88, std: 8 },
        { grade: 78, mean: 90, std: 5 },
      { grade: 88, mean: 85, std: 3 } ] }
    ]
  }
)

 

      • update

# update 
> db.runCommand( 
   { 
      update: <collection>, 
      updates: [ 
         { 
           q: <query>,   // q : 검색 해야 하는 내역 name이 Louis 인 것 (where 절)
           u: <document or pipeline>,   // u : 변경해야 하는 내역 (set 절)
           upsert: <boolean>,  // default : false (true로 변경 시 존재 하지 않으면 Insert 진행)
           multi: <boolean>,  // default : false (true로 변경 시 존재하는 모든 데이터에 대해 update 진행)
           collation: <document>, 
           arrayFilters: <array>, 
           hint: <document|string> 
         }, 
         ... 
      ], 
      ordered: <boolean>, 
      writeConcern: { <write concern> }, 
      bypassDocumentValidation: <boolean>, 
      comment: <any> 
   } 
)
> db.runCommand(  
    { 
        update : 'employee' 
        , updates : [ 
            { 
                q: {name : 'Louis'} 
                ,u : [{$set: {Post : ['DBA','Data Engineer'], wated:['Data Engineer']}}] 
            } 
        ] 
    } 
)

> db.runCommand(  
    { 
        update : 'employee' 
        , updates : [ 
            { 
                q: {name : 'DotDot'}  
                ,u : [{$set: {Post : ['DBA','Data Engineer'], wated:['Wanted Girl Friend']}}] 
            } 
        ] 
    } 
)

> db.runCommand(  
    { 
        update : 'employee' 
        , updates : [ 
            { 
                q: {name : 'DotDot'} 
                ,u : [{$set: {Post : ['DBA','Data Engineer'], wated:['Wanted Girl Friend']}}]
                ,upsert: true
            } 
        ] 
    } 
)

> db.runCommand({find:'employee', filter : {Post:'Data Engineer'}})

# multi 를 true로 변경 시 match 되는 모든 데이터가 변경
# 단, 내부에 여러건이 있을 경우 덮어 쓰기 때문에 이 점 유의
> db.runCommand(  
    { 
        update : 'employee' 
        , updates : [ 
            { 
                q: {Post:'Data Engineer'}  
                ,u : [{$set: {Post : ['Data Science']}}] 
                ,multi : true
            } 
        ] 
    } 
)
# multi 를 default (false)로 하는 경우 한 건만 변경
> db.runCommand(  
    { 
        update : 'employee' 
        , updates : [ 
            { 
                q: {Post:'Data Science'}  
                ,u : [{$set: {Post : ['Data Master']}}]  
            } 
        ] 
    } 
)
  • update

  • upsert

  • multi

 

      • find
        • Projection
          • 명시하고자 하는 field 를 결정 가능
          • 연산자를 사용도 가능
            • $
              • fileter 에서 조건이 걸린 것 중, 원하는 필드 내 (배열로 구성) 첫 번째 값 리턴
              • ex) filter 로 a= 1인 것 중 b.$:1 로 설정하는 경우 b필드 배열 중 제일 첫번째 값 리턴
            • $eleMatch
              • Embedded Documents 배열을 쿼리할 때 사용
            • $slice
              • Embedded Documents 배열을 쿼리의 결과에 대한 원하는 리턴 개수
            • $meta
> db.runCommand( 
   { 
      "find": <string>,  // find : collection 명
      "filter": <document>,  // 검색 하고자 하는 내용 (where) - 작성하지 않으면 해당 collection 모두 반환
      "sort": <document>,    // order by 
      "projection": <document>,   // 명시 하고자 하는 컬럼명 (필드 결정) 연산자를 사용 가능 
      "hint": <document or string>, 
      "skip": <int>,  // default : 0 - 건너뛴 Document 개수 이후의 모든 값 리턴
      "limit": <int>,  // default : no-limit / 처음부터 원하는 limit 개수
      "batchSize": <int>, // 배치에서 반환할 문서 수. Default : 101 개
      "singleBatch": <bool>, 
      "comment": <any>, 
      "maxTimeMS": <int>, 
      "readConcern": <document>, 
      "max": <document>, 
      "min": <document>, 
      "returnKey": <bool>, 
      "showRecordId": <bool>, 
      "tailable": <bool>, 
      "oplogReplay": <bool>, 
      "noCursorTimeout": <bool>, 
      "awaitData": <bool>, 
      "allowPartialResults": <bool>, 
      "collation": <document>, 
      "allowDiskUse" : <bool> 
   } 
)

# find 
> db.runCommand(  
    {  
        find : 'employee' 
        , filter : {name : 'Louis'} 
        , projection : {name : 1} 
    }  
) 
> db.runCommand(   
    {  
        find : 'employee'  
        , projection : {name : 1}  
    }  
) 
> db.runCommand(   
    {  
        find : 'employee'  
        , filter : {name : 'Louis'}  
        , projection : {name : 1}  
        , sort : {name : 1} 
        , limit : 1 
    }  
)
$ 테스트
> db.runCommand( 
     { 
         insert : 'employee' 
         , documents: 
             [ 
    { "_id" : 7, semester: 3, "grades" : [ { grade: 80, mean: 75, std: 8 }, 
                                           { grade: 85, mean: 90, std: 5 }, 
...                                        { grade: 90, mean: 85, std: 3 } ] } 
... , 
... { "_id" : 8, semester: 3, "grades" : [ { grade: 92, mean: 88, std: 8 }, 
...                                        { grade: 78, mean: 90, std: 5 }, 
...                                        { grade: 88, mean: 85, std: 3 } ] } 
...             ] 
...     } 
... )
-> grades.mean 이 > 70 중, 만족하는 grades 의 첫번째 배열 값 리턴
> db.students.find(  
   { "grades.mean": { $gt: 70 } }, 
   { "grades.$": 1 }  
)

결과
{ "_id" : 7, "grades" : [ { "grade" : 80, "mean" : 75, "std" : 8 } ] } 
{ "_id" : 8, "grades" : [ { "grade" : 92, "mean" : 88, "std" : 8 } ] }

  • {배열:{$elemMatch:{원하는필드: 값}}}
    • 원하는 정보가 있으면 배열 내 모든 값이 리턴

  • {배열:{$slice:원하는 리턴 개수}}
    • ex) 댓글의 최대 개수 리턴

      • delete
        • capped collections 에서는 동작하지 않음.
        • 그 외는 동일한 동작 방식
> db.runCommand(
    { 
       delete: <collection>,  // 삭제할 collaction 명
       deletes: [ 
          { 
            q : <query>,  // 조건
            limit : <integer>,  // 삭제 개수 필수 (0: 조건에 맞는 모든 데이터 삭제, 1~n : 조건에 맞는 n개 삭제)
            collation: <document>, 
            hint: <document|string>, 
            comment: <any> 
          }, 
          ... 
       ], 
       ordered: <boolean>, 
       writeConcern: { <write concern> } 
    }
)

# limit 을 미 작성 시 오류 발생
> db.runCommand( 
    {  
       delete: "students"
        , deletes : [
            {q: {"_id" : 7} , limit:1}
        ]
    }
)

#대응 하는 모든 데이터 삭제는 limit : 0 으로 설정
> db.runCommand( 
    {  
       delete: "students" 
        , deletes : [ 
            {q: {"semester" : 5} , limit:0} 
        ] 
    } 
)

# And 조건

> db.runCommand( 
    {  
       delete: "students" 
        , deletes : [ 
            {q: {"semester" : 5, "_id":1} , limit:0}  
        ] 
    } 
)

Command Type

Name

Description

Aggregation

aggregate

Performs aggregation tasks such as group using the aggregation framework.

count

Counts the number of documents in a collection or a view.

distinct

Displays the distinct values found for a specified key in a collection or a view.

mapReduce

Performs map-reduce aggregation for large data sets.

Geospatial 

geoSearch

Performs a geospatial query that uses MongoDB’s haystack index functionality.

Command

delete

Deletes one or more documents.

find

Selects documents in a collection or a view.

findAndModify

Returns and modifies a single document.

getLastError

Returns the success status of the last operation.

getMore

Returns batches of documents currently pointed to by the cursor.

insert

Inserts one or more documents.

resetError

Deprecated. Resets the last error status.

update

Updates one or more documents.

Query Plan Cache

planCacheClear

Removes cached query plan(s) for a collection.

planCacheClearFilters

Clears index filter(s) for a collection.

planCacheListFilters

Lists the index filters for a collection.

planCacheSetFilter

Sets an index filter for a collection.

Authentication

authenticate

Starts an authenticated session using a username and password.

getnonce

This is an internal command to generate a one-time password for authentication.

logout

Terminates the current authenticated session.

User Management

createUser

Creates a new user.

dropAllUsersFromDatabase

Deletes all users associated with a database.

dropUser

Removes a single user.

grantRolesToUser

Grants a role and its privileges to a user.

revokeRolesFromUser

Removes a role from a user.

updateUser

Updates a user’s data.

usersInfo

Returns information about the specified users.

Role Management

createRole

Creates a role and specifies its privileges.

dropRole

Deletes the user-defined role.

dropAllRolesFromDatabase

Deletes all user-defined roles from a database.

grantPrivilegesToRole

Assigns privileges to a user-defined role.

grantRolesToRole

Specifies roles from which a user-defined role inherits privileges.

invalidateUserCache

Flushes the in-memory cache of user information, including credentials and roles.

revokePrivilegesFromRole

Removes the specified privileges from a user-defined role.

revokeRolesFromRole

Removes specified inherited roles from a user-defined role.

rolesInfo

Returns information for the specified role or roles.

updateRole

Updates a user-defined role.

Replication

applyOps

Internal command that applies oplog entries to the current data set.

isMaster

Displays information about this member’s role in the replica set, including whether it is the master.

replSetAbortPrimaryCatchUp

Forces the elected primary to abort sync (catch up) then complete the transition to primary.

replSetFreeze

Prevents the current member from seeking election as primary for a period of time.

replSetGetConfig

Returns the replica set’s configuration object.

replSetGetStatus

Returns a document that reports on the status of the replica set.

replSetInitiate

Initializes a new replica set.

replSetMaintenance

Enables or disables a maintenance mode, which puts a secondary node in a RECOVERING state.

replSetReconfig

Applies a new configuration to an existing replica set.

replSetResizeOplog

Dynamically resizes the oplog for a replica set member. Available for WiredTiger storage engine only.

replSetStepDown

Forces the current primary to step down and become a secondary, forcing an election.

replSetSyncFrom

Explicitly override the default logic for selecting a member to replicate from.

Sharding

addShard

Adds a shard to a sharded cluster.

addShardToZone

Associates a shard with a zone. Supports configuring zones in sharded clusters.

balancerCollectionStatus

Returns information on whether the chunks of a sharded collection are balanced.

New in version 4.4.

balancerStart

Starts a balancer thread.

balancerStatus

Returns information on the balancer status.

balancerStop

Stops the balancer thread.

checkShardingIndex

Internal command that validates index on shard key.

clearJumboFlag

Clears the jumbo flag for a chunk.

cleanupOrphaned

Removes orphaned data with shard key values outside of the ranges of the chunks owned by a shard.

enableSharding

Enables sharding on a specific database.

flushRouterConfig

Forces a mongod/mongos instance to update its cached routing metadata.

getShardMap

Internal command that reports on the state of a sharded cluster.

getShardVersion

Internal command that returns the config server version.

isdbgrid

Verifies that a process is a mongos.

listShards

Returns a list of configured shards.

medianKey

Deprecated internal command. See splitVector.

moveChunk

Internal command that migrates chunks between shards.

movePrimary

Reassigns the primary shard when removing a shard from a sharded cluster.

mergeChunks

Provides the ability to combine chunks on a single shard.

refineCollectionShardKey

Refines a collection’s shard key by adding a suffix to the existing key.

New in version 4.4.

removeShard

Starts the process of removing a shard from a sharded cluster.

removeShardFromZone

Removes the association between a shard and a zone. Supports configuring zones in sharded clusters.

setShardVersion

Internal command to sets the config server version.

shardCollection

Enables the sharding functionality for a collection, allowing the collection to be sharded.

shardingState

Reports whether the mongod is a member of a sharded cluster.

split

Creates a new chunk.

splitChunk

Internal command to split chunk. Instead use the methods sh.splitFind() and sh.splitAt().

splitVector

Internal command that determines split points.

unsetSharding

Deprecated. Internal command that affects connections between instances in a MongoDB deployment.

updateZoneKeyRange

Adds or removes the association between a range of sharded data and a zone. Supports configuring zones in sharded clusters.

Session

abortTransaction

Abort transaction.

New in version 4.0.

commitTransaction

Commit transaction.

New in version 4.0.

endSessions

Expire sessions before the sessions’ timeout period.

New in version 3.6.

killAllSessions

Kill all sessions.

New in version 3.6.

killAllSessionsByPattern

Kill all sessions that match the specified pattern

New in version 3.6.

killSessions

Kill specified sessions.

New in version 3.6.

refreshSessions

Refresh idle sessions.

New in version 3.6.

startSession

Starts a new session.

New in version 3.6.

Administration   Commands

cloneCollectionAsCapped

Copies a non-capped collection as a new capped collection.

collMod

Add options to a collection or modify a view definition.

compact

Defragments a collection and rebuilds the indexes.

connPoolSync

Internal command to flush connection pool.

convertToCapped

Converts a non-capped collection to a capped collection.

create

Creates a collection or a view.

createIndexes

Builds one or more indexes for a collection.

currentOp

Returns a document that contains information on in-progress operations for the database instance.

drop

Removes the specified collection from the database.

dropDatabase

Removes the current database.

dropConnections

Drops outgoing connections to the specified list of hosts.

dropIndexes

Removes indexes from a collection.

filemd5

Returns the md5 hash for files stored using GridFS.

fsync

Flushes pending writes to the storage layer and locks the database to allow backups.

fsyncUnlock

Unlocks one fsync lock.

getDefaultRWConcern

Retrieves the global default read and write concern options for the deployment.

 

New in version 4.4.

getParameter

Retrieves configuration options.

killCursors

Kills the specified cursors for a collection.

killOp

Terminates an operation as specified by the operation ID.

listCollections

Returns a list of collections in the current database.

listDatabases

Returns a document that lists all databases and returns basic database statistics.

listIndexes

Lists all indexes for a collection.

logRotate

Rotates the MongoDB logs to prevent a single file from taking too much space.

reIndex

Rebuilds all indexes on a collection.

renameCollection

Changes the name of an existing collection.

setFeatureCompatibilityVersion

Enables or disables features that persist data that are backwards-incompatible.

setIndexCommitQuorum

Changes the minimum number of data-bearing members (i.e commit quorum), including the primary, that must vote to commit an in-progress index build before the primary marks those indexes as ready.

setParameter

Modifies configuration options.

setDefaultRWConcern

Sets the global default read and write concern options for the deployment.

 

New in version 4.4.

shutdown

Shuts down the mongod or mongos process.

 

Diagnostic Commands

availableQueryOptions

Internal command that reports on the capabilities of the current MongoDB instance.

buildInfo

Displays statistics about the MongoDB build.

collStats

Reports storage utilization statics for a specified collection.

connPoolStats

Reports statistics on the outgoing connections from this MongoDB instance to other MongoDB instances in the deployment.

connectionStatus

Reports the authentication state for the current connection.

cursorInfo

Removed in MongoDB 3.2. Replaced with metrics.cursor.

dataSize

Returns the data size for a range of data. For internal use.

dbHash

Returns hash value a database and its collections.

dbStats

Reports storage utilization statistics for the specified database.

driverOIDTest

Internal command that converts an ObjectId to a string to support tests.

explain

Returns information on the execution of various operations.

features

Reports on features available in the current MongoDB instance.

getCmdLineOpts

Returns a document with the run-time arguments to the MongoDB instance and their parsed options.

getLog

Returns recent log messages.

hostInfo

Returns data that reflects the underlying host system.

isSelf

Internal command to support testing.

listCommands

Lists all database commands provided by the current mongod instance.

lockInfo

Internal command that returns information on locks that are currently being held or pending. Only available for mongod instances.

netstat

Internal command that reports on intra-deployment connectivity. Only available for mongos instances.

ping

Internal command that tests intra-deployment connectivity.

profile

Interface for the database profiler.

serverStatus

Returns a collection metrics on instance-wide resource utilization and status.

shardConnPoolStats

Deprecated in 4.4 Use :dbcommand:`connPoolStats` instead.

 

Reports statistics on a mongos’s connection pool for client operations against shards.

top

Returns raw usage statistics for each database in the mongod instance.

validate

Internal command that scans for a collection’s data and indexes for correctness.

whatsmyuri

Internal command that returns information on the current client.

 

Free Monitoring Commands

setFreeMonitoring

Enables/disables free monitoring during runtime.

 

Auditing   Commands

logApplicationMessage

Posts a custom message to the audit log.

 

    • non-CRUD 명령어도 사용 가능
      • 통계 정보 가져오기
      • 복제본 세트 초기화
      • 집계 파이프라인
      • map-reduce 작업 모두 가능
# mongodb 의 역활 확인 (mster 여부)
> db.runCommand( { isMaster: 1 } )
{ 
         "ismaster" : true, 
        "maxBsonObjectSize" :16777216, 
        "localTime" :ISODate("2013-01-06T19:53:43.647Z"), 
        "ok" : 1 
}

 

 

반응형

+ Recent posts