반응형

기본 데이터 처리

  • 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