기본 데이터 처리
-
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 하기 때문에, 여기에 현재의 시간을 붙이는 방식으로 구현이 가능
-
CRUD
- Create, Read, Update, Delete
- "4주차 기본 명령어 익히기"에서 진행 했던 내용 참고([MongoDB][Study-4] MongoDB 기본 명령어 익히기)
- 그 중 runCommand 에 대해 추가 정리
-
runCommand
- Tool 에서 많이 보았던 command
- 지정한 DB에서 도우미 제공해 주는 명령어
- runCommand 를 사용하면, 내부 형태만 잡아 준다면 쉽게 접근이 가능
# 일반적으로 사용하는 명령어는 command 에 작성하여 사용 가능
# Default
> db.runCommand(
{
명령어
}
)
# 관리 administrative 명령어의 경우 아래와 같이 사용 가능
> db.adminCommand( { <command> } )
- 명령어 종류 (<command> 에 들어가는 명령어)
- https://docs.mongodb.com/manual/reference/command/
- 처음에 해당하는 첫 인자 값에는 실행할 명령어 (Insert, Update, Delete, Find 등)와 실행할 Collection 명 명시
-
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 |
Performs aggregation tasks such as group using the aggregation framework. |
|
Counts the number of documents in a collection or a view. |
||
Displays the distinct values found for a specified key in a collection or a view. |
||
Performs map-reduce aggregation for large data sets. |
||
Geospatial |
Performs a geospatial query that uses MongoDB’s haystack index functionality. |
|
Command |
Deletes one or more documents. |
|
Selects documents in a collection or a view. |
||
Returns and modifies a single document. |
||
Returns the success status of the last operation. |
||
Returns batches of documents currently pointed to by the cursor. |
||
Inserts one or more documents. |
||
Deprecated. Resets the last error status. |
||
Updates one or more documents. |
||
Query Plan Cache |
Removes cached query plan(s) for a collection. |
|
Clears index filter(s) for a collection. |
||
Lists the index filters for a collection. |
||
Sets an index filter for a collection. |
||
Authentication |
Starts an authenticated session using a username and password. |
|
This is an internal command to generate a one-time password for authentication. |
||
Terminates the current authenticated session. |
||
User Management |
Creates a new user. |
|
Deletes all users associated with a database. |
||
Removes a single user. |
||
Grants a role and its privileges to a user. |
||
Removes a role from a user. |
||
Updates a user’s data. |
||
Returns information about the specified users. |
||
Role Management |
Creates a role and specifies its privileges. |
|
Deletes the user-defined role. |
||
Deletes all user-defined roles from a database. |
||
Assigns privileges to a user-defined role. |
||
Specifies roles from which a user-defined role inherits privileges. |
||
Flushes the in-memory cache of user information, including credentials and roles. |
||
Removes the specified privileges from a user-defined role. |
||
Removes specified inherited roles from a user-defined role. |
||
Returns information for the specified role or roles. |
||
Updates a user-defined role. |
||
Replication |
Internal command that applies oplog entries to the current data set. |
|
Displays information about this member’s role in the replica set, including whether it is the master. |
||
Forces the elected primary to abort sync (catch up) then complete the transition to primary. |
||
Prevents the current member from seeking election as primary for a period of time. |
||
Returns the replica set’s configuration object. |
||
Returns a document that reports on the status of the replica set. |
||
Initializes a new replica set. |
||
Enables or disables a maintenance mode, which puts a secondary node in a RECOVERING state. |
||
Applies a new configuration to an existing replica set. |
||
Dynamically resizes the oplog for a replica set member. Available for WiredTiger storage engine only. |
||
Forces the current primary to step down and become a secondary, forcing an election. |
||
Explicitly override the default logic for selecting a member to replicate from. |
||
Sharding |
Adds a shard to a sharded cluster. |
|
Associates a shard with a zone. Supports configuring zones in sharded clusters. |
||
Returns information on whether the chunks of a sharded collection are balanced. New in version 4.4. |
||
Starts a balancer thread. |
||
Returns information on the balancer status. |
||
Stops the balancer thread. |
||
Internal command that validates index on shard key. |
||
Clears the jumbo flag for a chunk. |
||
Removes orphaned data with shard key values outside of the ranges of the chunks owned by a shard. |
||
Enables sharding on a specific database. |
||
Forces a mongod/mongos instance to update its cached routing metadata. |
||
Internal command that reports on the state of a sharded cluster. |
||
Internal command that returns the config server version. |
||
Verifies that a process is a mongos. |
||
Returns a list of configured shards. |
||
Deprecated internal command. See splitVector. |
||
Internal command that migrates chunks between shards. |
||
Reassigns the primary shard when removing a shard from a sharded cluster. |
||
Provides the ability to combine chunks on a single shard. |
||
Refines a collection’s shard key by adding a suffix to the existing key. New in version 4.4. |
||
Starts the process of removing a shard from a sharded cluster. |
||
Removes the association between a shard and a zone. Supports configuring zones in sharded clusters. |
||
Internal command to sets the config server version. |
||
Enables the sharding functionality for a collection, allowing the collection to be sharded. |
||
Reports whether the mongod is a member of a sharded cluster. |
||
Creates a new chunk. |
||
Internal command to split chunk. Instead use the methods sh.splitFind() and sh.splitAt(). |
||
Internal command that determines split points. |
||
Deprecated. Internal command that affects connections between instances in a MongoDB deployment. |
||
Adds or removes the association between a range of sharded data and a zone. Supports configuring zones in sharded clusters. |
||
Session |
Abort transaction. New in version 4.0. |
|
Commit transaction. New in version 4.0. |
||
Expire sessions before the sessions’ timeout period. New in version 3.6. |
||
Kill all sessions. New in version 3.6. |
||
Kill all sessions that match the specified pattern New in version 3.6. |
||
Kill specified sessions. New in version 3.6. |
||
Refresh idle sessions. New in version 3.6. |
||
Starts a new session. New in version 3.6. |
||
Administration Commands |
Copies a non-capped collection as a new capped collection. |
|
Add options to a collection or modify a view definition. |
||
Defragments a collection and rebuilds the indexes. |
||
Internal command to flush connection pool. |
||
Converts a non-capped collection to a capped collection. |
||
Creates a collection or a view. |
||
Builds one or more indexes for a collection. |
||
Returns a document that contains information on in-progress operations for the database instance. |
||
Removes the specified collection from the database. |
||
Removes the current database. |
||
Drops outgoing connections to the specified list of hosts. |
||
Removes indexes from a collection. |
||
Returns the md5 hash for files stored using GridFS. |
||
Flushes pending writes to the storage layer and locks the database to allow backups. |
||
Unlocks one fsync lock. |
||
Retrieves the global default read and write concern options for the deployment.
New in version 4.4. |
||
Retrieves configuration options. |
||
Kills the specified cursors for a collection. |
||
Terminates an operation as specified by the operation ID. |
||
Returns a list of collections in the current database. |
||
Returns a document that lists all databases and returns basic database statistics. |
||
Lists all indexes for a collection. |
||
Rotates the MongoDB logs to prevent a single file from taking too much space. |
||
Rebuilds all indexes on a collection. |
||
Changes the name of an existing collection. |
||
Enables or disables features that persist data that are backwards-incompatible. |
||
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. |
||
Modifies configuration options. |
||
Sets the global default read and write concern options for the deployment.
New in version 4.4. |
||
Shuts down the mongod or mongos process. |
||
Diagnostic Commands |
Internal command that reports on the capabilities of the current MongoDB instance. |
|
Displays statistics about the MongoDB build. |
||
Reports storage utilization statics for a specified collection. |
||
Reports statistics on the outgoing connections from this MongoDB instance to other MongoDB instances in the deployment. |
||
Reports the authentication state for the current connection. |
||
Removed in MongoDB 3.2. Replaced with metrics.cursor. |
||
Returns the data size for a range of data. For internal use. |
||
Returns hash value a database and its collections. |
||
Reports storage utilization statistics for the specified database. |
||
Internal command that converts an ObjectId to a string to support tests. |
||
Returns information on the execution of various operations. |
||
Reports on features available in the current MongoDB instance. |
||
Returns a document with the run-time arguments to the MongoDB instance and their parsed options. |
||
Returns recent log messages. |
||
Returns data that reflects the underlying host system. |
||
isSelf |
Internal command to support testing. |
|
Lists all database commands provided by the current mongod instance. |
||
Internal command that returns information on locks that are currently being held or pending. Only available for mongod instances. |
||
Internal command that reports on intra-deployment connectivity. Only available for mongos instances. |
||
Internal command that tests intra-deployment connectivity. |
||
Interface for the database profiler. |
||
Returns a collection metrics on instance-wide resource utilization and status. |
||
Deprecated in 4.4 Use :dbcommand:`connPoolStats` instead.
Reports statistics on a mongos’s connection pool for client operations against shards. |
||
Returns raw usage statistics for each database in the mongod instance. |
||
Internal command that scans for a collection’s data and indexes for correctness. |
||
Internal command that returns information on the current client. |
||
Free Monitoring Commands |
Enables/disables free monitoring during runtime. |
|
Auditing Commands |
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
}
'MongoDB > MongoDB-Study_완료' 카테고리의 다른 글
[MongoDB][Study-8] Aggregation (0) | 2021.04.16 |
---|---|
[MongoDB][Study-7] Find / FindAndModify / Cursor (0) | 2021.03.28 |
[MongoDB] [Study-Break] Cursor 간략한 정리 (0) | 2021.03.27 |
[MongoDB][Study-4] MongoDB 기본 명령어 익히기 (0) | 2021.03.27 |
[MongoDB][Study-3] Sharding (0) | 2021.03.27 |