### Collection Sharding API Source: https://www.mongodb.com/ko-kr/docs/manual/core/sharding-shard-a-collection This section details the `sh.shardCollection()` method used to shard a collection in MongoDB. It explains the required parameters: namespace and key, and provides examples for range-based and hashed sharding. ```APIDOC ## POST /sh.shardCollection ### Description Shards a collection by specifying its full namespace and shard key. This operation is crucial for distributing data across multiple shards in a MongoDB deployment. ### Method POST ### Endpoint `sh.shardCollection(, )` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **namespace** (string) - Required - The full namespace of the collection to shard, in the format `"."`. - **key** (object) - Required - A document specifying the shard key fields and their types. Use `1` for range-based sharding or `"hashed"` for hashed sharding. Example: `{ "field1": 1, "field2": "hashed" }`. ### Request Example ```json { "namespace": "mydatabase.mycollection", "key": { "_id": 1 } } ``` ### Response #### Success Response (200) - **ok** (number) - Indicates the success of the operation (usually 1). #### Response Example ```json { "ok": 1 } ``` ### Error Handling - **Error**: If the namespace is invalid or the shard key is improperly formatted, MongoDB will return an error indicating the issue. ``` -------------------------------- ### Example Document for Time Series Data Source: https://www.mongodb.com/ko-kr/docs/manual/core/timeseries/timeseries-bucketing This example demonstrates the structure of a document within a Time Series collection. It includes a timestamp, metadata relevant for bucketing (like sensor ID and type), and the actual data points. The `_id` field is shown but noted as not strictly necessary for Time Series collections. ```json { timestamp: ISODate("2021-05-18T00:00:00.000Z"), metadata: { sensorId: 5578, type: 'temperature' }, temp: 12, _id: ObjectId("62f11bbf1e52f124b84479ad") } ``` -------------------------------- ### 리샤딩 작업 모니터링 - MongoDB Shell Source: https://www.mongodb.com/ko-kr/docs/manual/core/sharding-reshard-a-collection 진행 중인 컬렉션 리샤딩 작업을 모니터링하는 데 사용됩니다. `$currentOp` 집계 파이프라인을 사용하여 현재 실행 중인 작업을 확인하고, `originatingCommand.reshardCollection` 필드를 통해 특정 컬렉션의 리샤딩 작업을 필터링합니다. ```javascript db.getSiblingDB("admin").aggregate([ { $currentOp: { allUsers: true, localOps: false } }, { $match: { type: "op", "originatingCommand.reshardCollection": "." } } ]) ``` -------------------------------- ### 진행 중인 인덱스 빌드 확인 - MongoDB Shell Source: https://www.mongodb.com/ko-kr/docs/manual/core/sharding-reshard-a-collection 컬렉션 리샤딩을 시작하기 전에 진행 중인 인덱스 빌드가 없는지 확인하는 데 사용됩니다. `$currentOp` 집계 파이프라인을 사용하여 현재 실행 중인 작업을 쿼리하고 인덱스 빌드 관련 작업을 필터링합니다. 결과 문서의 `inprog` 필드가 비어 있으면 진행 중인 인덱스 빌드가 없는 것입니다. ```javascript db.getSiblingDB("admin").aggregate( [ { $currentOp : { idleConnections: true } }, { $match: { $or: [ { "op": "command", "command.createIndexes": { $exists: true } }, { "op": "none", "msg": /^Index Build/ } ] } } ] ) ``` ```javascript { inprog: [], ok: 1, '$clusterTime': { ... }, operationTime: } ``` -------------------------------- ### 컬렉션 샤딩 - mongosh Source: https://www.mongodb.com/ko-kr/docs/manual/core/sharding-shard-a-collection mongosh 메서드 sh.shardCollection()를 사용하여 컬렉션을 샤딩합니다. 이 메서드는 샤딩하려는 컬렉션의 전체 네임스페이스와 샤드 키를 지정합니다. 샤드 키는 범위 기반 샤딩을 나타내는 1 또는 해시된 샤딩을 나타내는 "hashed"를 포함할 수 있습니다. ```javascript sh.shardCollection(".", { : 1, ... }) sh.shardCollection(".", { : "hashed", ... }) ``` -------------------------------- ### MongoDB 샤드 키 세분화 명령 Source: https://www.mongodb.com/ko-kr/docs/manual/core/sharding-data-partitioning refineCollectionShardKey 명령은 컬렉션의 샤드 키를 세분화하는 데 사용됩니다. 이를 통해 데이터를 더 세밀하게 분배하고, 기존 키의 카디널리티 부족으로 인한 점보 청크 문제를 해결할 수 있습니다. 이 명령은 MongoDB 5.0부터 사용할 수 있습니다. ```javascript db.runCommand({ refineCollectionShardKey: "", key: { : } }) ``` -------------------------------- ### MongoDB 샤드 컬렉션 및 분산 Source: https://www.mongodb.com/ko-kr/docs/manual/core/sharding-data-partitioning sh.shardCollection() 메서드는 컬렉션의 데이터를 클러스터의 다른 샤드에 분배하기 시작합니다. 이 과정에서 밸런서가 작동하여 데이터를 균등하게 분산시킵니다. 각 샤드는 한 번에 하나의 청크 마이그레이션에만 참여할 수 있습니다. ```javascript sh.shardCollection("", "") ``` -------------------------------- ### 컬렉션 리샤딩 시작 - MongoDB Shell Source: https://www.mongodb.com/ko-kr/docs/manual/core/sharding-reshard-a-collection 컬렉션 리샤딩 작업을 시작하는 데 사용되는 `reshardCollection` 관리 명령입니다. 데이터베이스와 컬렉션 이름, 그리고 새로운 샤드 키를 지정해야 합니다. `forceRedistribution` 옵션을 `true`로 설정하면 동일한 샤드 키로 리샤딩할 수 있습니다. ```javascript db.adminCommand({ reshardCollection: ".", key: }) ``` ```javascript db.adminCommand({ reshardCollection: ".", key: , forceRedistribution: true }) ``` -------------------------------- ### MongoDB 테일 커서 쿼리 예시 Source: https://www.mongodb.com/ko-kr/docs/manual/core/tailable-cursors 인덱스 필드의 마지막 값을 사용하여 새로 추가된 문서를 조회하는 쿼리 예시입니다. 테일 커서 대신 일반 커서를 사용할 때 새로 추가된 문서를 추적하는 방법을 보여줍니다. ```javascript db..find( { indexedField: { $gt: } } ) ``` -------------------------------- ### MongoDB: 문서의 샤드 키 값 업데이트 (updateOne) Source: https://www.mongodb.com/ko-kr/docs/manual/core/sharding-change-shard-key-value MongoDB에서 `updateOne` 메서드를 사용하여 문서의 샤드 키 값을 업데이트하는 예시입니다. 이 작업은 샤드 키 필드가 `_id`가 아닌 경우에만 가능하며, 트랜잭션 또는 재시도 가능 쓰기 내에서 실행해야 합니다. ```javascript db.sales.updateOne( { _id: 12345, location: "" }, { $set: { location: "New York"} } ) ``` -------------------------------- ### MongoDB 테일 커서 생성 (mongosh) Source: https://www.mongodb.com/ko-kr/docs/manual/core/tailable-cursors mongosh에서 테일 커서를 생성하는 방법을 보여줍니다. 이 메서드는 고정 사이즈 컬렉션에서 새로 추가되는 문서를 지속적으로 조회할 때 사용됩니다. ```javascript db..find( { indexedField: { $gt: } } ).tailable() ``` -------------------------------- ### MongoDB 샤드 컬렉션 상태 확인 Source: https://www.mongodb.com/ko-kr/docs/manual/core/sharding-data-partitioning sh.balancerCollectionStatus() 명령은 MongoDB 샤딩된 컬렉션의 밸런서 상태를 확인하는 데 사용됩니다. 이 명령은 밸런서가 활성화되어 있는지, 현재 컬렉션의 샤딩 상태는 어떤지 등의 정보를 제공합니다. ```javascript sh.balancerCollectionStatus() ``` -------------------------------- ### Inserting Documents with Consistent Field Order (MongoDB) Source: https://www.mongodb.com/ko-kr/docs/manual/core/timeseries/timeseries-best-practices Demonstrates inserting documents into a Time Series collection with a consistent field order for optimal performance. Inconsistent field order can lead to suboptimal performance. ```javascript db.collection.insertMany([ { _id: ObjectId("6250a0ef02a1877734a9df57"), timestamp: ISODate("2020-01-23T00:00:00.441Z"), name: "sensor1", range: 1 }, { _id: ObjectId("6560a0ef02a1877734a9df66"), timestamp: ISODate("2020-01-23T01:00:00.441Z"), name: "sensor1", range: 5 } ]) ``` ```javascript db.collection.insertMany([ { range: 1, _id: ObjectId("6250a0ef02a1877734a9df57"), name: "sensor1", timestamp: ISODate("2020-01-23T00:00:00.441Z") }, { _id: ObjectId("6560a0ef02a1877734a9df66"), name: "sensor1", timestamp: ISODate("2020-01-23T01:00:00.441Z"), range: 5 } ]) ``` -------------------------------- ### Monitor Resharding Operation with $currentOp Source: https://www.mongodb.com/ko-kr/docs/manual/core/sharding-reshard-a-collection This snippet shows the expected output structure from the `$currentOp` aggregation pipeline when monitoring a resharding operation. It includes fields like `totalOperationTimeElapsedSecs` and `remainingOperationTimeEstimatedSecs` to track the operation's progress. This is useful for understanding the status of a resharding task. ```json [ { "shard": "", "type": "op", "desc": "ReshardingRecipientService | ReshardingDonorService | ReshardingCoordinatorService ", "op": "command", "ns": ".", "originatingCommand": { "reshardCollection": ".", "key": , "unique": , "collation": { "locale": "simple" } }, "totalOperationTimeElapsedSecs": , "remainingOperationTimeEstimatedSecs": , "...": "..." }, ... ] ``` -------------------------------- ### MongoDB 컬렉션 샤딩 및 즉시 리샤딩 Source: https://www.mongodb.com/ko-kr/docs/manual/core/sharding-data-partitioning sh.shardAndDistributeCollection() 메서드는 컬렉션을 샤드하고 즉시 동일한 키로 다시 샤딩하는 MongoDB 8.0 이상 버전에서 권장되는 방식입니다. 이 메서드는 sh.shardCollection() 및 reshardCollection 명령을 래핑하여 밸런서 대기 없이 샤드 전체에서 데이터를 리밸런싱합니다. ```javascript sh.shardAndDistributeCollection("", "") ``` -------------------------------- ### MongoDB Time Series 컬렉션: 빈 필드 생략으로 압축 최적화 Source: https://www.mongodb.com/ko-kr/docs/manual/core/timeseries/timeseries-best-practices 문서에서 빈 객체, 배열 또는 문자열이 포함된 필드를 생략하여 Time Series 컬렉션의 압축을 최적화합니다. 이렇게 하면 스키마 변경으로 인해 문서가 압축되지 않은 상태로 유지되는 것을 방지할 수 있습니다. ```javascript db.temperatures.insertMany([ { timestamp: ISODate("2021-05-18T00:00:00.000Z"), temperature: 10 }, { timestamp: ISODate("2021-05-19T00:00:00.000Z"), temperature: 12 }, { timestamp: ISODate("2021-05-20T00:00:00.000Z"), temperature: 13 }, { timestamp: ISODate("2021-05-18T00:00:00.000Z"), temperature: 20 }, { timestamp: ISODate("2021-05-19T00:00:00.000Z"), temperature: 25 }, { metadField: { sensor: "sensorB" }, timestamp: ISODate("2021-05-20T00:00:00.000Z"), temperature: 26 } ], { "ordered": false } ) ```