

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 遷移至 Amazon DocumentDB
<a name="docdb-migration"></a>

Amazon DocumentDB 是與 MongoDB API 相容的全受管資料庫服務。您可以使用本節詳述的程序，將資料從內部部署或 Amazon Elastic Compute Cloud (Amazon EC2) 上執行的 MongoDB 資料庫遷移至 Amazon DocumentDB。 MongoDB Amazon EC2

**Topics**
+ [快速入門指南](migration-quick-start.md)
+ [遷移 Runbook](docdb-migration-runbook.md)
+ [從 Couchbase Server 遷移](migration-from-couchbase.md)

# 使用 AWS Database Migration Service (DMS) 遷移至 Amazon DocumentDB：快速入門指南
<a name="migration-quick-start"></a>

**Topics**
+ [準備 DMS 來源](#migrate-qs-dma-source)
+ [設定 DMS](#migrate-qs-dms-setup)
+ [啟用 DocumentDB 壓縮](#migrate-qs-comp)
+ [建立複寫任務](#migrate-qs-create)
+ [監控進度](#migrate-qs-monitor)
+ [其他資訊](#migrate-qs-info)

## 準備 DMS 來源
<a name="migrate-qs-dma-source"></a>

請參閱 [啟用變更串流](change_streams.md#change_streams-enabling) 以啟用 DocumentDB 變更串流，或啟用 MongoDB Oplog 以支援 DMS 變更資料擷取 (CDC)。
+ DMS 來源必須保留所有持續變更，直到所有包含集合的 DMS 完全載入完成為止。
+ DocumentDB 變更串流以時間為基礎。請確定您的`change_stream_log_retention_duration`設定夠大，足以涵蓋完成完整載入的時間。
+ MongoDB Oplog 是固定大小。確定其大小足以在完全載入期間保留所有操作。

## 設定 DMS
<a name="migrate-qs-dms-setup"></a>

建立 DMS 執行個體、來源和目標端點，並測試每個端點。

## 啟用 DocumentDB 壓縮
<a name="migrate-qs-comp"></a>

將自訂參數群組連接至 DocumentDB 叢集，並將 default\$1collection\$1compression 參數更新為已啟用，以啟用壓縮。如需詳細資訊，請參閱[管理集合層級文件壓縮](doc-compression.md)。

## 建立複寫任務
<a name="migrate-qs-create"></a>

1. 在 DMS 主控台的導覽窗格中，選擇**遷移或複寫**，然後選擇**任務**。

1. 選擇 **Create task (建立任務)**。

1. 在**建立任務**頁面上的任務**組態**區段中：
   + 輸入唯一且有意義的**任務識別符** （例如，「mongodb-docdb-replication」)。
   + 選擇您先前在來源**資料庫端點下拉式功能表中建立的來源端點**。
   + 選擇您先前在目標**資料庫端點下拉式功能表中建立的目標端點**。
   + 針對**任務類型**，選擇**遷移和複寫**。

1. 在**設定**區段中：
   + 對於**任務日誌**，勾選**開啟 CloudWatch** 日誌方塊。
   + 對於**編輯模式 **（在區段頂端），選擇 **JSON 編輯器**並設定下列屬性：
     + `ParallelApplyThreads` 設定為 5 （在 下`TargetMetadata`)。這會在 CDC 中啟用每秒約 1000 個 insert/update/delete ops。
     + `MaxFullLoadSubTasks` 設定為 16 （在 下`FullLoadSettings`)。考慮根據您的執行個體大小增加此值。
     + 對於大型集合 （超過 100 GB)，啟用自動分割 （在資料表映射下和 `parallel-load` 屬性下）：
       + "type"： "partitions-auto"
       + 「number-of-partitions」：16

## 監控進度
<a name="migrate-qs-monitor"></a>

使用 AWS DMS 主控台或建立自訂儀表板 ([儀表板工具](https://github.com/awslabs/amazon-documentdb-tools/tree/master/monitoring/docdb-dashboarder)) 來追蹤遷移。專注於下列指標：
+ **FullLoadThroughputBandwidthTarget** — 在遷移的完整載入階段期間，測量 DMS 在將資料傳輸至目標資料庫時所使用的網路頻寬 （以 KB/秒為單位）。
+ **CDCLatencyTarget** — 測量來源資料庫中發生變更，以及將該變更套用至目標資料庫時的時間延遲 （以秒為單位）。
+ **CDCThroughputRowsTarget** — 在遷移的持續複寫階段，測量 DMS 每秒套用至目標資料庫的資料列數。

## 其他資訊
<a name="migrate-qs-info"></a>

如需 Amazon DocumentDB 和 的詳細資訊 AWS DMS，請參閱：如需詳細資訊，請參閱 。
+ [Amazon DocumentDB 遷移 Runbook](docdb-migration-runbook.md)
+ [從 MongoDB 遷移至 Amazon DocumentDB](https://docs.aws.amazon.com/dms/latest/sbs/chap-mongodb2documentdb.html)

# Amazon DocumentDB 遷移 Runbook
<a name="docdb-migration-runbook"></a>

此 Runbook 提供使用 AWS Database Migration Service (DMS) 將 MongoDB 資料庫遷移至 Amazon DocumentDB 的完整指南。它旨在在整個end-to-end遷移過程中支援資料庫管理員、雲端工程師和開發人員，從初始探索到遷移後驗證。

鑑於 MongoDB 和 Amazon DocumentDB 之間的實作和支援功能差異，此 Runbook 強調結構化和系統化的方法。它概述了必要的遷移前評估、強調相容性考量，並詳細說明確保成功遷移所需的關鍵任務，並將中斷降至最低。

Runbook 會組織成下列主題：
+ **[相容性](#mig-runbook-compatibility)** — 了解 Amazon DocumentDB 中支援的 MongoDB 功能和資料類型，並識別潛在的不相容。
+ **[工作負載探索](#mig-runbook-workload)** — 分析現有的 MongoDB 工作負載，包括讀取/寫入模式、資料磁碟區和效能基準。
+ **[索引遷移](#mig-runbook-index)** — 分析擷取和轉換 MongoDB 索引的策略，以在 Amazon DocumentDB 中獲得最佳效能。
+ **[使用者遷移](#mig-runbook-user)** — 詳細說明將資料庫使用者、角色和存取控制遷移至 Amazon DocumentDB 的方法。
+ **[資料遷移](#mig-runbook-data)** — 涵蓋各種使用 進行資料遷移的方法 AWS DMS，包括完全載入和變更資料擷取 (CDC)。
+ **[監控](#mig-runbook-monitoring)** — 詳細說明使用 DMS 或原生工具遷移時的各種監控方法。
+ **[驗證](#mig-runbook-validation)** — 提供遷移後資料完整性檢查、功能驗證和效能比較的程序。

透過遵循此 Runbook 中的指引，團隊可以確保順利、安全且有效率地轉換至 Amazon DocumentDB，同時保留應用程式功能並將風險降至最低。

## 相容性
<a name="mig-runbook-compatibility"></a>

**Topics**
+ [核心功能相容性](#w2aac23b9c13c13)
+ [Amazon DocumentDB 相容性評估工具](#w2aac23b9c13c15)

從 MongoDB 遷移至 Amazon DocumentDB 時，完整的初始評估和功能相容性檢查對於成功遷移至關重要。此程序從 MongoDB 功能的全面清查開始，包括彙總管道運算子、查詢模式、索引和資料模型。

由於 Amazon DocumentDB 與 MongoDB 3.6、4.0、5.0 和 8.0 API 相容，因此使用較新 MongoDB 特定功能的應用程式可能需要重構。要評估的關鍵領域包括碎片機制 (Amazon DocumentDB 使用不同的方法）、交易實作、變更串流功能和索引類型 （特別是稀疏和部分索引）。

效能特性也有所不同，Amazon DocumentDB 已針對具有可預測效能的企業工作負載進行最佳化。測試應涉及對兩個系統執行代表性工作負載，以識別可能需要最佳化的查詢模式。

在評估階段期間，監控執行計畫以偵測潛在的效能差距非常重要。這有助於建立明確的遷移路線圖、識別必要的應用程式變更，並建立逼真的時間表，以便順利轉換。

### 核心功能相容性
<a name="w2aac23b9c13c13"></a>



#### 全方位功能支援
<a name="w2aac23b9c13c13b5"></a>
+ **CRUD 操作** — 享受對所有基本建立、讀取、更新和刪除操作的完整支援，包括大量和查詢運算子 - 提供無縫的應用程式相容性。
+ **豐富的索引功能** — 利用對單一欄位、複合、TTL、部分、稀疏和 2dsphere 索引的全面支援，以最佳化文字型查詢的查詢效能和文字索引 （第 5 版）。
+ **企業級複寫** — 受益於強大的自動容錯移轉機制，其具有僅供讀取複本，可提供卓越的高可用性，而無需營運開銷。
+ **進階備份解決方案** — 使用具有Point-in-Time復原 (PITR) 的自動備份系統以及用於資料保護的隨需手動快照，輕鬆休息。

#### 增強 AWS整合功能
<a name="w2aac23b9c13c13b7"></a>
+ **簡化彙總** — 利用最常用的彙總階段 (`$match`、`$sort`、、 `$project`等）`$group`，並針對企業工作負載最佳化效能。
+ **交易支援** — 實作多文件和多集合交易，非常適合大多數商業應用程式需求。
+ **即時資料追蹤** — 透過簡單的命令啟用變更串流，並透過簡單的參數群組設定來增加變更串流保留期間，以進行即時資料變更監控。
+ **位置型服務** — 實作地理空間應用程式，並支援`$geoNear`運算子和 2dsphere 索引。
+ **文字搜尋功能** — 利用內建的文字搜尋功能來滿足內容探索需求。

#### 現代架構優勢
<a name="w2aac23b9c13c13b9"></a>
+ **雲端原生設計** — AWS享受最佳化的架構，可將 MapReduce 等傳統功能取代為更有效率的彙總管道操作。
+ **增強安全性** — 受益於 AWS Identity and Access Management (IAM)SCRAM-SHA-1, SCRAM-SHA-256、X.509 憑證身分驗證和密碼型身分驗證。
+ **可預測效能** — 體驗專為企業工作負載最佳化的一致效能。

如需 Amazon DocumentDB 功能的完整概觀，請參閱 [Amazon DocumentDB 中支援的 MongoDB APIs、操作和資料類型](mongo-apis.md)和 [功能差異：Amazon DocumentDB 和 MongoDB](functional-differences.md) 以最大化資料庫的潛力。

Amazon DocumentDB 不支援 MongoDB 提供的所有索引。我們提供免費的[索引工具](https://github.com/awslabs/amazon-documentdb-tools/blob/master/index-tool/README.md)來檢查相容性。我們建議您執行索引工具，以評估不相容並相應地規劃解決方法。

### Amazon DocumentDB 相容性評估工具
<a name="w2aac23b9c13c15"></a>

[MongoDB 到 Amazon DocumentDB 相容性工具](https://github.com/awslabs/amazon-documentdb-tools/blob/master/compat-tool/README.md)是 GitHub 上提供的開放原始碼公用程式，可透過分析 MongoDB 日誌或應用程式原始程式碼，協助評估 MongoDB 工作負載與 Amazon DocumentDB 的相容性。

**主要功能**
+ 識別工作負載中的 MongoDB API 使用模式
+ 在遷移之前標記潛在的相容性問題
+ 產生詳細的相容性報告與建議
+ 可作為可在本機執行的獨立公用程式

#### 評估方法
<a name="w2aac23b9c13c15b9"></a>

**以日誌為基礎的評估**


+ 優點：
  + 擷取實際執行時間行為和查詢模式
  + 識別實際使用頻率和效能特性
  + 偵測來源碼中可能看不到的動態查詢
  + 不需要存取應用程式原始碼
+ 缺點：
  + 需要存取已啟用分析的 MongoDB 日誌
  + 僅擷取記錄期間發生的操作
  + 可能遺漏不常使用的功能或季節性工作負載

**原始程式碼分析**


+ 優點：
  + 全面涵蓋程式碼庫中所有潛在的 MongoDB 操作
  + 可以識別很少執行的程式碼路徑中的問題
  + 偵測可能受 Amazon DocumentDB 差異影響的用戶端邏輯
  + 不需要執行應用程式即可執行評估
+ 缺點：
  + 可能標記已存在但從未在生產環境中執行的程式碼
  + 需要存取才能完成應用程式原始碼
  + 分析動態建構查詢的能力有限

為了獲得最佳結果，我們建議您盡可能使用兩種評估方法，以在遷移之前完整了解相容性挑戰。

## 工作負載探索
<a name="mig-runbook-workload"></a>

從 MongoDB 遷移至 Amazon DocumentDB 需要徹底了解現有的資料庫工作負載。工作負載探索是分析資料庫使用模式、資料結構、查詢效能和操作相依性的程序，以確保無縫轉換，並將中斷降至最低。本節概述工作負載探索所涉及的關鍵步驟，以促進從 MongoDB 到 Amazon DocumentDB 的有效遷移。

**Topics**
+ [評估現有的 MongoDB 部署](#w2aac23b9c15b7)
+ [識別資料模型差異](#w2aac23b9c15b9)
+ [查詢和效能分析](#w2aac23b9c15c11)
+ [安全性和存取控制檢閱](#w2aac23b9c15c13)
+ [操作和監控考量](#w2aac23b9c15c15)

### 評估現有的 MongoDB 部署
<a name="w2aac23b9c15b7"></a>

在遷移之前，評估目前的 MongoDB 環境至關重要，包括：
+ **叢集架構** — 識別節點、複本集和碎片組態的數量。從 MongoDB 遷移至 Amazon DocumentDB 時，了解 MongoDB 碎片組態很重要，因為 Amazon DocumentDB 不支援使用者控制的碎片。專為碎片 MongoDB 環境設計的應用程式將需要架構變更，因為 Amazon DocumentDB 在其儲存型架構中使用不同的擴展方法。移至 Amazon DocumentDB 時，您將需要調整資料分佈策略，並可能合併碎片集合。
+ **儲存和資料磁碟區** — 測量叢集的總資料大小和索引大小。使用 [Oplog 檢閱工具](https://github.com/awslabs/amazon-documentdb-tools/tree/master/migration/mongodb-oplog-review)補充這一點，以了解寫入模式和資料成長速度。如需調整叢集大小的詳細資訊，請參閱[執行個體大小調整](best_practices.md#best_practices-instance_sizing)。
+ **工作負載模式** — 分析讀取和寫入輸送量、查詢執行頻率和索引效率。
+ **操作相依性** — 記錄依賴 MongoDB 的所有應用程式、服務和整合。

### 識別資料模型差異
<a name="w2aac23b9c15b9"></a>

雖然 Amazon DocumentDB 與 MongoDB 相容，但支援的功能存在差異，例如：
+ **交易** — Amazon DocumentDB 支援 ACID 交易，但有一些 [限制](transactions.md#transactions-limitations)。
+ **結構描述設計** — 確保文件結構、內嵌文件和參考符合 [Amazon DocumentDB 的最佳實務](https://d1.awsstatic.com/product-marketing/Data%20modeling%20with%20Amazon%20DocumentDB.pdf)。

### 查詢和效能分析
<a name="w2aac23b9c15c11"></a>

了解查詢行為有助於最佳化遷移和遷移後效能。要分析的關鍵領域包括：
+ **緩慢查詢** — 使用 MongoDB 的分析工具識別具有高執行時間的查詢。
+ **查詢模式** — 分類常見的查詢類型，包括 CRUD 操作和彙總。
+ **索引用量** — 評估索引是否有效使用，或是否需要在 Amazon DocumentDB 中最佳化。若要評估 Amazon DocumentDB 中的索引用量並最佳化效能，請在關鍵查詢上使用`$indexStats`彙總管道階段結合 `explain()`方法。首先執行 `db.collection.aggregate([{$indexStats{}}])`以識別正在使用的索引。您可以使用 執行最常用的查詢，以執行更詳細的分析`explainPlan`。
+ **並行和工作負載分佈** — 評估讀取和寫入比率、連線集區和效能瓶頸。

### 安全性和存取控制檢閱
<a name="w2aac23b9c15c13"></a>

**身分驗證和授權**
+ **MongoDB RBAC 到 Amazon DocumentDB IAM 和 RBAC** — 將 MongoDB 的角色型存取控制使用者和角色映射到 AWS Identity and Access Management (IAM) 政策和 Amazon DocumentDB SCRAM 身分驗證使用者。
+ **使用者遷移策略** — 規劃將資料庫使用者、自訂角色和權限遷移至 Amazon DocumentDB 支援的身分驗證機制。
+ **權限差異** — 識別沒有直接 Amazon DocumentDB 對等項目的 MongoDB 權限 （例如，叢集管理角色）。 Amazon DocumentDB 
+ **應用程式身分驗證** — 更新 Amazon DocumentDB 密碼政策的連線字串和憑證管理。您可以使用秘密管理員來存放您的登入資料並輪換密碼。
+ **服務帳戶管理** — 建立管理服務帳戶登入資料的程序 AWS Secrets Manager。
+ **最低權限實作** — 檢閱和精簡存取控制，以在新環境中實作最低權限原則。

**加密**

確保靜態加密和傳輸中加密符合合規要求。

**網路組態**

規劃 [Virtual Private Cloud (VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/create-vpc.html) 設定和安全群組規則。

### 操作和監控考量
<a name="w2aac23b9c15c15"></a>

為了維護系統可靠性，工作負載探索也應該包含：
+ **備份和還原策略** — 評估現有的備份方法和 Amazon DocumentDB 的備份功能。
+ **AWS Backup 整合** — 利用 AWS Backup 跨 AWS 服務集中備份管理，包括 Amazon DocumentDB。
+ **CloudWatch 指標** — 將 MongoDB 監控指標映射至 CPU、記憶體、連線和儲存體的 Amazon DocumentDB CloudWatch 指標。
+ **績效詳情** — 實作 Amazon DocumentDB 績效詳情，透過詳細的查詢分析視覺化資料庫負載和分析效能問題。
+ **Profiler** — 設定 Amazon DocumentDB Profiler 以擷取慢速執行的操作 （類似於 MongoDB 的 Profiler，但使用 Amazon DocumentDB 特定設定）。
  + 透過具有適當閾值的參數群組啟用 。
  + 分析分析分析器資料以識別最佳化機會
+ **CloudWatch Events** — 設定 Amazon DocumentDB 叢集事件的事件驅動型監控。
  + 設定備份事件、維護時段和容錯移轉的通知。
  + 與 Amazon SNS 整合，用於提醒和 AWS Lambda 自動回應。
+ **稽核記錄** — 規劃稽核記錄組態，以追蹤使用者活動和安全相關事件。
+ **增強型監控** — 以 1 秒的間隔為精細作業系統層級指標啟用增強型監控。

## 索引遷移
<a name="mig-runbook-index"></a>

從 MongoDB 遷移到 Amazon DocumentDB 不僅需要傳輸資料，還包括索引，以維持查詢效能並最佳化資料庫操作。本節概述將索引從 MongoDB 遷移至 Amazon DocumentDB 的詳細step-by-step程序，同時確保相容性和效率。

### 使用 Amazon DocumentDB 索引工具
<a name="w2aac23b9c17b5"></a>

**複製[索引工具](https://github.com/awslabs/amazon-documentdb-tools/blob/master/index-tool/README.md)**

```
git clone https://github.com/aws-samples/amazon-documentdb-tools.git
cd amazon-documentdb-tools/index-tool
```

```
pip install -r requirements.txt
```

**從 MongoDB 匯出索引 （如果從 MongoDB 遷移）**

```
python3 migrationtools/documentdb_index_tool.py --dump-indexes --dir mongodb_index_export --uri
'mongodb://localhost:27017'
```

**從 Amazon DocumentDB 匯出索引 （如果從 Amazon DocumentDB 遷移）**

```
python3 migrationtools/documentdb_index_tool.py --dump-indexes --dir docdb_index_export --uri
'mongodb://user:password@mydocdb.cluster-cdtjj00yfi95.eu-west-
2.docdb.amazonaws.com:27017/?tls=true&tlsCAFile=rds-combined-ca-
bundle.pem&replicaSet=rs0&retryWrites=false'
```

**匯入索引**

```
python3 migrationtools/documentdb_index_tool.py --restore-indexes --skip-incompatible --dir
mongodb_index_export --uri 'mongodb://user:password@mydocdb.cluster-cdtjj00yfi95.eu-west-
2.docdb.amazonaws.com:27017/?tls=true&tlsCAFile=rds-combined-ca-
bundle.pem&replicaSet=rs0&retryWrites=false'
```

**驗證索引**

```
python3 migrationtools/documentdb_index_tool.py --show-issues --dir mongodb_index_export
```

## 使用者遷移
<a name="mig-runbook-user"></a>

將使用者從 MongoDB 遷移至 Amazon DocumentDB 是維護存取控制、身分驗證和資料庫安全性的必要條件。本節概述了使用 Amazon DocumentDB 匯出使用者工具成功遷移 MongoDB 使用者，同時保留其角色和許可的詳細步驟。

### 使用 Amazon DocumentDB 匯出使用者工具
<a name="w2aac23b9c19b5"></a>

從 MongoDB 或 Amazon DocumentDB [https://github.com/awslabs/amazon-documentdb-tools/tree/master/migration/export-users](https://github.com/awslabs/amazon-documentdb-tools/tree/master/migration/export-users) 匯出使用者和角色到 JavaScript 檔案，然後可用於在另一個叢集中重新建立它們。

**先決條件**

```
# Clone the repository
git clone https://github.com/awslabs/amazon-documentdb-tools.git
cd amazon-documentdb-tools/migration/export-users
```

```
# Install required dependencies
pip install pymongo
```

**步驟 1：匯出使用者和角色**

```
# Export users and roles to JavaScript files
python3 docdbExportUsers.py \
--users-file mongodb-users.js \
--roles-file mongodb-roles.js \
--uri "mongodb://admin:password@source-host:27017/"
```

**步驟 2：編輯使用者檔案**

```
// Example of how to update the users.js file
// Find each user creation statement and add the password
db.getSiblingDB("admin").createUser({
user: "appuser",
// Add password here
pwd: "newpassword",
roles: [
{ role: "readWrite", db: "mydb" }
]
})
```

**步驟 3：將自訂角色還原至 Amazon DocumentDB**

```
# Import roles first
mongo --ssl \
--host target-host:27017 \
--sslCAFile rds-combined-ca-bundle.pem \
--username admin \
--password password \
mongodb-roles.js
```

**步驟 4：將使用者還原至 Amazon DocumentDB**

```
# Import users after roles are created
mongo --ssl \
--host target-host:27017 \
--sslCAFile rds-combined-ca-bundle.pem \
--username admin \
--password password \
mongodb-users.js
```

**重要說明**
+ 基於安全考量，密碼不會匯出，而且必須手動新增至 user.js 檔案。
+ 必須在使用者之前匯入角色，以確保適當的角色指派。
+ 此工具會產生可直接使用 mongo shell 執行的 JavaScript 檔案。
+ 自訂角色及其權限會在遷移期間保留。
+ 此方法允許在匯入之前檢閱和修改使用者許可。

此方法提供安全且靈活的方法，可將使用者和角色從 MongoDB 遷移至 Amazon DocumentDB，同時允許在遷移程序期間重設密碼。

## 資料遷移
<a name="mig-runbook-data"></a>

**Topics**
+ [線上遷移](#w2aac23b9c21b5)
+ [離線移轉](#w2aac23b9c21b7)
+ [先決條件](#w2aac23b9c21c11)
+ [準備 Amazon DocumentDB 叢集](#w2aac23b9c21c13)
+ [執行資料傾印 (mongodump)](#w2aac23b9c21c15)
+ [將傾印檔案傳輸到還原環境](#w2aac23b9c21c17)
+ [將資料還原至 Amazon DocumentDB (mongorestore)](#w2aac23b9c21c19)

### 線上遷移
<a name="w2aac23b9c21b5"></a>

本節提供使用 執行從 MongoDB 到 Amazon DocumentDB 線上遷移的詳細步驟 AWS DMS ，以盡可能減少停機時間和持續複寫。首先，您將 Amazon DocumentDB 叢集設定為目標，並確保 MongoDB 執行個體已正確設定為來源，通常需要複本集模式才能擷取變更資料。接著，您可以建立 DMS 複寫執行個體，並使用必要的連線詳細資訊定義來源和目標端點。驗證端點之後，您可以設定並啟動遷移任務，其中包含完整資料載入、持續複寫或兩者。

#### 設定目標 (Amazon DocumentDB)
<a name="w2aac23b9c21b5b5"></a>

**注意**  
如果您已佈建要遷移到的 Amazon DocumentDB 叢集，您可以略過此步驟。

**建立自訂參數群組**

請參閱 中的 AWS 管理主控台 或 AWS CLI 程序[建立 Amazon DocumentDB 叢集參數群組](cluster_parameter_groups-create.md)。

**建立 Amazon DocumentDB 叢集**

**注意**  
雖然本指南中有建立 Amazon DocumentDB 叢集的其他程序，但本節中的步驟特別適用於將大量資料遷移至新叢集的任務。

1. 登入 AWS 管理主控台，並在 https：//[https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb) 開啟 Amazon DocumentDB 主控台。

1. 在導覽窗格中，選擇**叢集**。
**提示**  
如果畫面左側沒有出現導覽窗格，請選擇頁面左上角的功能表圖示 (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/zh_tw/documentdb/latest/developerguide/images/docdb-menu-icon.png))。

1. 在 Amazon DocumentDB 管理主控台的**叢集**下，選擇**建立**。

1. 在**建立 Amazon DocumentDB 叢集**頁面上的**叢集類型**區段中，選擇**執行個體型叢集** （這是預設選項）。

1. 在叢集組態區段中：
   + 針對**叢集識別符**，輸入唯一名稱，例如 **mydocdbcluster**。請注意，無論如何輸入叢集名稱，主控台都會將所有叢集名稱變更為小寫。
   + 針對**引擎版本**，選擇 5.0.0。

1. 在**叢集儲存組態**區段中，將 **Amazon DocumentDB 標準**設定保持原狀 （這是預設選項）。

1. 在**執行個體組態**區段中：
   + 針對**資料庫執行個體類別**，選擇**記憶體最佳化類別 （包括 r 類別）** （這是預設值）。
   + 針對**執行個體類別**，根據工作負載選擇執行個體類別。例如：
     + db.r6g.large：適用於較小的工作負載
     + db.r6g.4xlarge：適用於大型工作負載

     最佳實務是，我們建議您盡可能選擇大的執行個體，以獲得最佳完全載入輸送量，並在遷移完成後縮減規模。
   + 針對**執行個體數量**，選擇 1 個執行個體。選擇一個執行個體有助於將成本降至最低。我們建議您在完全載入遷移完成後擴展到三個執行個體，以獲得高可用性。

1. 在**身分驗證**區段中，輸入主要使用者的使用者名稱，然後選擇**自我管理**。輸入密碼，然後進行確認。

1. 在**網路設定**區段中，選擇 VPC 和子網路群組，然後設定 VPC 安全群組。透過更新傳入規則，確保您的 Amazon DocumentDB 安全群組允許來自 DMS 執行個體安全群組的傳入連線。

1. 在**Encryption-at-rest**區段中，啟用加密 （建議），然後選擇或輸入 KMS 金鑰。

1. 在**備份**區段中，設定備份保留期 (1-35 天）。

1.  檢閱您的組態，然後選擇**建立叢集**。

   部署時間通常需要 10 到 15 分鐘，

#### 設定來源
<a name="w2aac23b9c21b5b7"></a>

MongoDB 和 Amazon DocumentDB 都可以做為遷移來源，視您的案例而定：
+ **MongoDB 作為來源** — 從內部部署或自我管理的 MongoDB 遷移到 Amazon DocumentDB 或其他 AWS 資料庫服務時很常見。需要在具有適當大小的 oplog 的複本集模式下執行 （確保其大小在完全載入期間保留所有操作），以支援遷移期間的變更資料擷取。
+ **Amazon DocumentDB 作為來源** — 通常用於跨區域複寫、版本升級或遷移至其他資料庫服務，例如 MongoDB Atlas。需要[啟用變更串流](change_streams.md#change_streams-enabling)在叢集`change_stream_log_retention_duration`參數群組中設定 參數，以擷取遷移期間持續的變更。請確定您的`change_stream_log_retention_duration`設定夠大，足以涵蓋完成完整載入所需的時間。

開始遷移之前，請將您的來源設定為允許 AWS DMS 存取。

建立具有適當許可的 MongoDB 使用者：

```
db.createUser({
user: "dmsUser",
pwd: "yourSecurePassword",
roles: [{ role: "readAnyDatabase", db: "admin" }]
})
```

設定網路和身分驗證。

設定 MongoDB 到 DMS 遷移的網路連線時：

**EC2-hosted MongoDB 來源**
+ 修改 EC2 安全群組，以允許來自 DMS 複寫執行個體安全群組的傳入流量。
+ 新增 TCP 連接埠 27017 （或您的自訂 MongoDB 連接埠） 的規則。
+ 使用 DMS 複寫執行個體的安全群組 ID 做為精確存取控制的來源。
+ 確保 EC2 執行個體的子網路具有 DMS 複寫執行個體子網路的路由。

**內部部署 MongoDB 來源**
+ 設定防火牆以允許來自 DMS 複寫執行個體公有 IP 地址的傳入連線。
+ 如果使用 Direct Connect 或 VPN，請確保網路與包含 DMS 執行個體的 VPC 之間的適當路由。
+ 使用 telnet 或 nc 命令測試從 DMS 子網路到 MongoDB 伺服器的連線。

**MongoDB Atlas 來源**
+ 將 DMS 複寫執行個體 IP 地址新增至 MongoDB Atlas IP 允許清單。
+ 如果 Atlas 正在執行，請在 AWS VPC 和 MongoDB Atlas VPC 之間設定 VPC 對等互連 AWS。
+ 如果在其他雲端提供者上執行，請設定 AWS PrivateLink 私有連線 (Enterprise 層）。
+ 建立具有適當讀取/寫入許可的專用使用者。
+ 使用將 SSL 模式設定為 "verify-full" 的 MongoDB Atlas 連線字串。
+ 確保遷移持續時間有足夠的 oplog 大小。

**Amazon DocumentDB 來源**

設定來源 Amazon DocumentDB 安全群組，以允許來自 DMS 複寫執行個體安全群組的傳入流量。

#### 建立 DMS 複寫執行個體
<a name="w2aac23b9c21b5b9"></a>

我們建議您使用 [DMS Buddy](https://github.com/awslabs/amazon-documentdb-tools/tree/master/migration/dms_buddy) 來佈建 DMS 基礎設施，因為它會建立具有最佳 DMS 設定和執行個體大小的最佳遷移基礎設施。

如果您想要手動設定 ，請依照下列步驟進行：

1. 開啟 AWS DMS 主控台，然後選擇**建立複寫執行個體**。

1. 輸入複寫執行個體詳細資訊：
   + **執行個體名稱**：選擇唯一的名稱。
   + **執行個體類別**：根據工作負載選取 。範例：dms.r5.large （小型工作負載）、dms.r5.4xlarge （大型工作負載）。
   + **引擎版本**：3.5.4
   + **配置的儲存**：預設值為 100GB （視需要增加）。這取決於文件大小、更新/秒和完全載入持續時間。
   + **異地同步備份部署**：視需要啟用 以獲得高可用性。
   + 選擇與 Amazon DocumentDB 相同的 VPC。
   + 確保**安全群組**允許來自來源和 Amazon DocumentDB 的傳入流量。

1. 按一下**建立複寫執行個體**，並等待狀態可用。

#### 建立 DMS 端點
<a name="w2aac23b9c21b5c11"></a>

##### 建立來源端點
<a name="w2aac23b9c21b5c11b3"></a>

**對於 MongoDB 來源**

1. 在 DMS 主控台的導覽窗格中，選擇**遷移或複寫**，然後選擇**端點**。

1. 選擇**建立端點**。

1. 在**建立端點**頁面上，選擇**來源端點**。

1. 在**端點組態**區段中：
   + 輸入唯一且有意義的**端點識別符** （例如，「mongodb-source」)。
   + 選擇 **MongoDB** 做為**來源引擎**。
   + 對於**端點資料庫的存取**，選擇**手動提供存取資訊**。
   + 在**伺服器名稱**中，輸入您的 *MongoDB 伺服器 DNS 名稱/IP 地址*。
   + 針對**連接埠**，輸入 **27017** （預設 MongoDB 連接埠）。
   + 對於**身分驗證模式**，為您的應用程式選擇適當的模式 （密碼/SSL) （預設為 Secrets Manager)。
   + 如果**身分驗證模式**是**密碼**，請提供：
     + **使用者名稱和密碼******：輸入 MongoDB 登入資料。
     + **資料庫名稱**：您的來源資料庫名稱。
     + **身分驗證機制**：SCRAM-SHA-1 （預設） 或適當的機制

1. 對於**中繼資料模式**，請保留 **文件**的預設設定。

1. 其他連線屬性：
   + authSource=admin （如果身分驗證資料庫不同）
   + replicaSet=<your-replica-set-name> (CDC 需要）

**對於 Amazon DocumentDB 來源**

1. 在 DMS 主控台的導覽窗格中，選擇**遷移或複寫**，然後選擇**端點**。

1. 選擇**建立端點**。

1. 在**建立端點**頁面上，選擇**來源端點**。

1. 在**端點組態**區段中：
   + 輸入唯一且有意義的**端點識別符** （例如 "docdb-source")。
   + 選擇 **Amazon DocumentDB** 做為**來源引擎**。
   + 對於**端點資料庫的存取**，選擇**手動提供存取資訊**。
   + 在**伺服器名稱**中，輸入您的*來源 Amazon DocumentDB 叢集端點*。
   + 針對**連接埠**，輸入 **27017** （預設 Amazon DocumentDB 連接埠）。
   + 對於 **SSL 模式**，選擇 **verify-full** （建議用於 Amazon DocumentDB)。
   + 針對 **CA 憑證**，選擇 Amazon RDS 根 CA 憑證。
   + 對於**身分驗證模式**，為您的應用程式選擇適當的模式 （密碼/SSL) （預設為 Secrets Manager)。
   + 如果**身分驗證模式**是**密碼**，請提供：
     + **使用者名稱和密碼******：輸入 Amazon DocumentDB 登入資料。
     + **資料庫名稱**：您的來源資料庫名稱。
     + **身分驗證機制**：SCRAM-SHA-1 （預設） 或適當的機制

1. 對於**中繼資料模式**，請保留 **文件**的預設設定。

##### 建立目標端點 (Amazon DocumentDB)
<a name="w2aac23b9c21b5c11b5"></a>

1. 在 DMS 主控台的導覽窗格中，選擇**遷移或複寫**，然後選擇**端點**。

1. 選擇**建立端點**。

1. 在**建立端點**頁面上，選擇**目標端點**。

1. 在**端點組態**區段中：
   + 輸入唯一且有意義的**端點識別符** （例如 "docdb-target")。
   + 選擇 **Amazon DocumentDB** 作為**目標引擎**。
   + 針對**端點資料庫的存取**，選擇您要用來驗證資料庫存取的方法：
     + 如果您選擇 **AWS Secrets Manager**，請在 Secret 欄位中選擇存放 Amazon DocumentDB 登入資料的**秘密**。
     + 如果您選擇**手動提供存取資訊**：
       + 在**伺服器名稱**中，輸入您的*目標 Amazon DocumentDB 叢集端點*。
       + 針對**連接埠**，輸入 **27017** （預設 Amazon DocumentDB 連接埠）。
       + 對於 **SSL 模式**，選擇 **verify-full** （建議用於 Amazon DocumentDB)。
       + 對於 **CA 憑證**，請下載並指定用於 SSL 驗證的 CA 憑證套件。
       + 對於**身分驗證模式**，為您的應用程式選擇適當的模式 （密碼/SSL) （預設為 Secrets Manager)。
       + 如果**身分驗證模式**是**密碼**，請提供：
         + **使用者名稱和密碼******：輸入 Amazon DocumentDB 登入資料。
         + **資料庫名稱**：您的來源資料庫名稱。
         + **身分驗證機制**：SCRAM-SHA-1 （預設） 或適當的機制

1. 對於**中繼資料模式**，請保留 **文件**的預設設定。

#### 建立複寫任務
<a name="w2aac23b9c21b5c13"></a>

1. 在 DMS 主控台的導覽窗格中，選擇**遷移或複寫**，然後選擇**任務**。

1. 選擇 **Create task (建立任務)**。

1. 在**建立任務**頁面上的任務**組態**區段中：
   + 輸入唯一且有意義的**任務識別符** （例如，「mongodb-docdb-replication」)。
   + 選擇您先前在來源**資料庫端點下拉式功能表中建立的來源端點**。
   + 選擇您先前在目標**資料庫端點下拉式功能表中建立的目標端點**。
   + 針對**任務類型**，選擇**遷移和複寫**。

1. 在**設定**區段中：
   + 對於**目標資料表準備模式**，請保留預設設定。
   + 對於**完全載入完成後的停止任務**，請保留預設設定。
   + 對於 **LOB 欄設定**，請將**有限 LOB 模式**設定保持原狀。
   + 對於**資料驗證**，將預設設定保留**為關閉**。
   + 對於**任務日誌**，勾選**開啟 CloudWatch** 日誌方塊。
   + 對於**批次最佳化套用**，請保留未勾選的預設設定 （關閉）。

1. 回到**任務設定**區段頂端，在**編輯模式中**，選擇 **JSON 編輯器**並設定下列屬性：

   ```
   {
     "TargetMetadata": {
       "ParallelApplyThreads": 5
     },
     "FullLoadSettings": {
       "MaxFullLoadSubTasks": 16
     }
   }
   ```

1. 在**資料表映射**區段中，新增新的選取規則：
   + 針對**結構描述名稱**，新增要遷移的來源資料庫。使用 % 指定多個資料庫。
   + 針對**結構描述資料表**名稱，新增要遷移的來源集合。使用 % 指定多個集合。
   + 對於**動作**，保留 **Include** 的預設設定

1. 對於大型集合 （超過 100GB)，新增**資料表設定規則**：
   + 針對**結構描述名稱**，新增要遷移的來源資料庫。使用 % 指定多個資料庫。
   + 針對**結構描述資料表**名稱，新增要遷移的來源集合。使用 % 指定多個集合。
   + 針對**分割區數量**，輸入 16 （應小於 `MaxFullLoadSubTask`)。

1. 在**預遷移評估**區段中，確定已關閉。

### 離線移轉
<a name="w2aac23b9c21b7"></a>

本節概述使用原生 MongoDB 工具從自我管理的 MongoDB 執行個體執行離線遷移至 Amazon DocumentDB MongoDB 的程序： `mongodump`和 `mongorestore`。

### 先決條件
<a name="w2aac23b9c21c11"></a>

**來源 MongoDB 需求**
+ 使用適當的許可存取來源 MongoDB 執行個體。
+ 視需要安裝 `mongodump`。 （會在 MongoDB 安裝期間安裝）。
+ 請確定傾印檔案有足夠的磁碟空間。

**目標 Amazon DocumentDB 需求**
+ 請確定您已佈建 Amazon DocumentDB 叢集。
+ 確保與 Amazon DocumentDB 相同的 VPC 中有 EC2 執行個體，以利遷移。
+ 您的來源環境和 Amazon DocumentDB 之間必須具備網路連線能力。
+ **mongorestore** 必須安裝在遷移 EC2 執行個體上。
+ 必須設定適當的 IAM 許可來存取 Amazon DocumentDB、

**一般要求**
+ AWS CLI 必須設定 （如果使用 AWS 服務進行中繼儲存）
+ 必須有足夠的頻寬才能進行資料傳輸。
+ 應核准停機時間時段 （如果進行即時遷移，請考慮其他方法）

### 準備 Amazon DocumentDB 叢集
<a name="w2aac23b9c21c13"></a>

在 中建立 Amazon DocumentDB 叢集 AWS：
+ 根據您的工作負載適當調整執行個體大小。
+ 設定 VPC、子網路和安全群組。
+ 透過參數群組啟用必要的參數。

### 執行資料傾印 (mongodump)
<a name="w2aac23b9c21c15"></a>

選擇下列其中一個選項來建立傾印檔案：
+ **選項 1：基本**

  ```
  mongodump --
  uri="mongodb://<source_user>:<source_password>@<source_host>:<source_port>/<database>" --
  out=/path/to/dump
  ```
+ **選項 2：更好的控制和效能**

  ```
  mongodump \
  --uri="mongodb://<source_user>:<source_password>@<sourcehost>:<source_port>" \
  --out=/path/to/dump \
  --gzip \# Compress output
  --numParallelCollections=4 \# Parallel collections dump
  --ssl \# If using SSL
  --authenticationDatabase=admin \ # If auth is required
  --readPreference=secondaryPreferred # If replica set
  ```
+ **選項 3：大型資料庫**

  ```
  mongodump \
  --host=<source_host> \
  --port=<source_port> \
  --username=<source_user> \
  --password=<source_password> \
  --db=<specific_db> \# Only dump specific DB
  --collection=<specific_collection> \ # Only dump specific collection
  --query='{ "date": { "$gt": "2020-01-01" } }' \ # Filter documents
  --archive=/path/to/archive.gz \# Single archive output
  --gzip \
  --ssl
  ```

### 將傾印檔案傳輸到還原環境
<a name="w2aac23b9c21c17"></a>

根據您的傾印大小選擇適當的方法：
+ **小型**：直接複製到遷移機器 （您先前建立的 EC2 執行個體）：

  ```
  scp -r /path/to/dump user@migration-machine:/path/to/restore
  ```
+ **中** — 使用 Amazon S3 作為中繼儲存：

  ```
  aws s3 cp --recursive /path/to/dump s3://your-bucket/mongodb-dump/
  ```
+ **大型** — 對於非常大型的資料庫，請考慮 AWS DataSync 或實體傳輸。

### 將資料還原至 Amazon DocumentDB (mongorestore)
<a name="w2aac23b9c21c19"></a>

開始還原程序之前，請在 Amazon DocumentDB 中建立索引。您可以使用 [Amazon DocumentDB 索引工具](https://github.com/awslabs/amazon-documentdb-tools/tree/master/index-tool)來匯出和匯入索引。

選擇下列其中一個選項來還原資料：
+ **選項 1：基本還原**

  ```
  mongorestore --uri="mongodb://<docdb_user>:<docdb_password>@<docdb_endpoint>:27017"
  /path/to/dump
  ```
+ **選項 2：更好的控制和效能**

  ```
  mongorestore \
  --uri="mongodb://<docdb_user>:<docdb_password>@<docdb_endpoint>:27017" \
  --ssl \
  --sslCAFile=/path/to/rds-combined-ca-bundle.pem \ # DocumentDB CA cert
  --gzip \# If dumped with gzip
  --numParallelCollections=4 \# Parallel restoration
  --numInsertionWorkersPerCollection=4 \# Parallel documents insertion
  --noIndexRestore \# skip indexes as they are pre-created
  /path/to/dump
  ```
+ **選項 3：大型資料庫或特定控制項**

  ```
  mongorestore \
  --host=<docdb_endpoint> \
  --port=27017 \
  --username=<docdb_user> \
  --password=<docdb_password> \
  --ssl \
  --sslCAFile=/path/to/rds-combined-ca-bundle.pem \
  --archive=/path/to/archive.gz \# If using archive format
  --gzip \
  --nsInclude="db1.*" \# Only restore specific namespaces
  --nsExclude="db1.sensitive_data" \ # Exclude specific collections if needed
  --noIndexRestore \# skip indexes as they are pre-created
  --writeConcern="{w: 'majority'}" # Ensure write durability
  ```

## 監控
<a name="mig-runbook-monitoring"></a>

本節提供詳細的監控程序，以追蹤持續遷移的進度、效能和運作狀態：

**MongoDB** 到 **Amazon DocumentDB**

或

**Amazon DocumentDB** 到 **Amazon DocumentDB**

無論遷移方法為何 (AWS DMS、mongodump/mongorestore 或其他工具），都會套用監控步驟。

### AWS DMS 遷移監控 （如適用）
<a name="w2aac23b9c23c13"></a>

監控下列關鍵 CloudWatch 指標：

**完全載入階段指標**
+ **FullLoadThroughputBandwidthTarget** — 完全載入期間的網路頻寬 (KB/秒）
+ **FullLoadThroughputRowsTarget** — 每秒載入的資料列/文件數
+ **FullLoadThroughputTablesTarget** — 每分鐘完成的資料表/集合數量
+ **FullLoadProgressPercent** — 已完成完全載入的百分比
+ **TablesLoaded** — 成功載入的資料表/集合數目
+ **TablesLoading** — 目前正在載入的資料表/集合數量
+ **TablesQueued** — 等待載入的資料表/集合數目
+ **TablesErrored** — 無法載入的資料表/集合數量

**CDC 階段指標**
+ **CDCLatencyTarget** — 來源變更與目標應用程式之間的時間延遲 （秒）
+ **CDCLatencySource** — 來源變更和 DMS 讀取之間的時間延遲 （秒）
+ **CDCThroughputRowsTarget** — 持續複寫期間每秒套用的資料列數
+ **CDCThroughputBandwidthTarget** — CDC 期間的網路頻寬 (KB/秒）
+ **CDCIncomingChanges** — 從來源接收的變更事件數目
+ **CDCChangesMemoryTarget** — 用於儲存目標端變更的記憶體 (MB)

**資源指標**
+ **CPUUtilization** — 複寫執行個體的 CPU 用量
+ **FreeableMemory** — 複寫執行個體上的可用記憶體
+ **FreeStorageSpace** — 複寫執行個體上的可用儲存體
+ **NetworkTransmitThroughput** — 複寫執行個體的網路輸送量
+ **NetworkReceiveThroughput** — 複寫執行個體的網路輸送量

**錯誤指標**
+ **ErrorsCount** — 遷移期間的錯誤總數
+ **TableErrorsCount** — 資料表特定錯誤的數量
+ **RecordsErrorsCount** — 記錄特定錯誤的數量

為 `CDCLatencyTarget`和 等關鍵指標建立 CloudWatch 警示`CPUUtilization`，以便在遷移效能降低時接收通知。

#### DMS 日誌 (CloudWatch 日誌）
<a name="w2aac23b9c23c13c23"></a>



1. 前往 Amazon CloudWatch Logs 主控台。

1. 在您的日誌群組上尋找並選擇 。它看起來類似於「dms-tasks –」。

1. 尋找可能包含錯誤資訊的日誌串流：
   + 名稱中有「錯誤」的串流
   + 具有任務 IDs串流
   + 遷移期間的最新日誌串流

1. 在這些串流中，搜尋關鍵字，例如：
   + 「錯誤」
   + 「例外狀況」
   + 「失敗」
   + 「警告」

#### DMS 任務狀態 （使用 AWS CLI)
<a name="w2aac23b9c23c13c25"></a>



```
aws dms describe-replication-tasks --filters Name=replication-task id,Values=<task_id> --query
"ReplicationTasks[0].Status"
```

預期的狀態流程：

建立 → ready → 執行中 → 停止 → 已停止 （或失敗）

#### 使用 監控 `docdb-dashboarder`
<a name="w2aac23b9c23c13c27"></a>

該`docdb-dashboarder`工具透過自動產生具有基本效能指標的 CloudWatch 儀表板，為 Amazon DocumentDB 叢集提供全面的監控。這些儀表板會顯示關鍵叢集層級指標 （複本延遲、操作計數器）、執行個體層級指標 (CPU、記憶體、連線） 和儲存指標 （磁碟區使用量、備份儲存）。對於遷移案例，該工具提供專門的儀表板，使用 CDC 複寫延遲和操作速率等指標來追蹤遷移進度。儀表板可以同時監控多個叢集，並包含對 NVMe 後端執行個體的支援。透過視覺化這些指標，團隊可以主動識別效能瓶頸、最佳化資源配置，並確保其 Amazon DocumentDB 部署的順暢操作。該工具無需手動建立儀表板，同時在所有環境中提供一致的監控。如需設定說明和進階組態選項，請參閱 [Amazon DocumentDB Dashboarder Tool](https://github.com/awslabs/amazon-documentdb-tools/tree/master/monitoring/docdb-dashboarder) GitHub 儲存庫。

## 驗證
<a name="mig-runbook-validation"></a>

**Topics**
+ [驗證檢查清單](#w2aac23b9c25c15)
+ [結構描述和索引驗證](#w2aac23b9c25c17)
+ [資料取樣和欄位層級驗證](#w2aac23b9c25c19)
+ [使用 DataDiffer 工具進行驗證](#w2aac23b9c25c21)

本節提供詳細的驗證程序，以確保從下列位置遷移後的資料一致性、完整性和應用程式相容性：

**MongoDB** 到 **Amazon DocumentDB**

或

**Amazon DocumentDB** 到 **Amazon DocumentDB**

無論遷移方法為何 (AWS DMS、mongodump/mongorestore 或其他工具），驗證步驟都適用。

### 驗證檢查清單
<a name="w2aac23b9c25c15"></a>

確認每個集合中的文件數量符合來源和目標：

**MongoDB 來源**

```
mongo --host <source_host> --port <port> --username <user> -- password <password> --eval
"db.<collection>.count()"
```

**Amazon DocumentDB 目標**

```
mongo --host <target_host> --port <port> --username <user> -- password <password> --eval
"db.<collection>.count()"
```

### 結構描述和索引驗證
<a name="w2aac23b9c25c17"></a>

請確認以下事項：
+ 目標中存在所有集合。
+ 索引已正確複寫。
+ 結構描述定義 （如果強制執行） 完全相同。

**檢查集合 （來源與目標）**

```
mongo --host <source_host> --eval "show collections"
mongo --host <target_host> --ssl --eval "show collections"
```

**檢查索引 （來源與目標）**

```
mongo --host <source_host> --eval" db.<collection>.getIndexes()"
mongo --host <target_host> --ssl –eval" db.<collection>.getIndexes()"
```

比較集合清單，以確保沒有遺漏或額外的集合。

透過檢查索引名稱、索引鍵定義、唯一限制條件和 TTL 索引 （如果有的話） 來驗證索引。

**檢查結構描述驗證規則 （如果在 MongoDB 中使用結構描述驗證）**

```
mongo --host <source_host> --eval" db.getCollectionInfos({name: '<collection>'})
[0].options.validator"
   mongo --host <target_host> --ssl –eval" db.getCollectionInfos({name: '<collection>'})[0].options.validator"
```

### 資料取樣和欄位層級驗證
<a name="w2aac23b9c25c19"></a>

您可以隨機取樣文件，並比較來源和目標之間的欄位。

**手動取樣**

擷取五個隨機文件 （來源）：

```
mongo --host <source_host> --eval "db.<collection>.aggregate([{ \$sample: { size: 5 } }])"
```

擷取相同的文件 IDs（目標）：

```
mongo --host <target_host> --ssl –eval "db.<collection>.find({ _id: { \$in: [<list_of_ids>] } })"
```

**自動取樣**

```
import pymongo
# Connect to source and target
source_client = pymongo.MongoClient("<source_uri>")
target_client = pymongo.MongoClient("<target_uri>", ssl=True)
source_db = source_client["<db_name>"]
target_db = target_client["<db_name>"]
# Compare 100 random documents
for doc in source_db.<collection>.aggregate([{ "$sample":
{ "size": 100 } }]):
target_doc = target_db.<collection>.find_one({ "_id":
doc["_id"] })
if target_doc != doc:
print(f"❌ Mismatch in _id: {doc['_id']}")
else:
print(f"✅ Match: {doc['_id']}")
```

### 使用 DataDiffer 工具進行驗證
<a name="w2aac23b9c25c21"></a>

[DataDiffer 工具](https://github.com/awslabs/amazon-documentdb-tools/tree/master/migration/data-differ)提供可靠的方法來比較來源和目標資料庫之間的資料。

#### 先決條件
<a name="w2aac23b9c25c21b5"></a>

安裝 DataDiffer 工具之前，必須符合下列先決條件：
+ Python 3.7\$1
+ PyMongo 程式庫
+ 與來源 MongoDB 和目標 Amazon DocumentDB 叢集的網路連線

#### 設定和安裝
<a name="w2aac23b9c25c21b7"></a>

**複製儲存庫並導覽至 DataDiffer 目錄**

```
git clone https://github.com/awslabs/amazon-documentdb-tools.git
cd amazon-documentdb-tools/migration/data-differ
```

**安裝必要的相依性**

```
pip install -r requirements.txt
```

#### 執行資料驗證
<a name="w2aac23b9c25c21b9"></a>

**建立包含連線詳細資訊的組態檔案 （例如 config.json)**

```
{
"source": {
"uri": "mongodb://username:password@source-mongodb-
host:27017/?replicaSet=rs0",
"db": "your_database",
"collection": "your_collection"
},
"target": {
"uri": "mongodb://username:password@target-docdb-
cluster.region.docdb.amazonaws.com:27017/?tls=true&tlsCAFile=global-
bundle.pem&replicaSet=rs0",
"db": "your_database",
"collection": "your_collection"
},
"options": {
"batch_size": 1000,
"threads": 4,
"sample_size": 0,
"verbose": true
}
}
```

**執行 DataDiffer 工具**

```
python differ.py --config config.json
```

**對於大型集合，請使用抽樣來驗證資料子集**

```
python differ.py --config config.json --sample-size 10000
```

**若要驗證多個集合，請建立個別的組態檔案或使用批次模式**

```
python differ.py --batch-config batch_config.json
```

#### 解譯結果
<a name="w2aac23b9c25c21c11"></a>

工具將輸出：
+ 來源和目標中的文件總數
+ 相符的文件數量
+ 遺失的文件數量
+ 有差異的文件數量
+ 差異的詳細報告 （如果有的話）

#### 最佳實務
<a name="w2aac23b9c25c21c13"></a>

以下是使用 DataDiffer 工具時的最佳實務：
+ **分階段執行** — 首先驗證文件計數，然後範例金鑰文件，並視需要執行完整比較。
+ **檢查結構描述差異** — 相較於 MongoDBAmazon DocumentDB 有一些限制。工具會反白顯示不相容的資料類型或結構。
+ 在**靜止期間驗證** — 在寫入操作最少時執行驗證，以確保一致性。
+ **監控資源用量** — 比較程序可能會耗費大量資源。相應地調整批次大小和執行緒計數。
+ **驗證索引** — 驗證資料之後，請確定已在目標 Amazon DocumentDB 叢集上建立所有必要的索引。
+ **文件驗證結果** — 將每個集合的驗證結果記錄為遷移文件的一部分。

# 從 Couchbase Server 遷移
<a name="migration-from-couchbase"></a>

**Topics**
+ [簡介](#introduction)
+ [與 Amazon DocumentDB 的比較](#comparison-to-amazon-documentdb)
+ [探索](#discovery)
+ [規劃](#planning)
+ [移轉](#migration)
+ [驗證](#validation)

## 簡介
<a name="introduction"></a>

本指南介紹從 Couchbase Server 遷移至 Amazon DocumentDB 時要考量的要點。它說明遷移探索、規劃、執行和驗證階段的考量。它還說明如何執行離線和線上遷移。

## 與 Amazon DocumentDB 的比較
<a name="comparison-to-amazon-documentdb"></a>


|  | **Couchbase 伺服器** | **Amazon DocumentDB** | 
| --- | --- | --- | 
| 資料組織 | 在 7.0 版和更新版本中，資料會組織成儲存貯體、範圍和集合。在舊版中，資料會組織成儲存貯體。 | 資料會組織成資料庫和集合。 | 
| 相容性 | 每個服務都有不同的 APIs（例如資料、索引、搜尋等）。次要查詢使用 SQL\$1\$1 （先前稱為 N1QL)，這是一種以 ANSI 標準 SQL 為基礎的查詢語言，因此許多開發人員都很熟悉。 | Amazon DocumentDB [與 MongoDB API 相容](compatibility.html)。 | 
| 架構 | 儲存體會連接至每個叢集執行個體。您無法獨立於儲存體擴展運算。 | Amazon DocumentDB 專為雲端而設計，可避免傳統資料庫架構的限制。[運算和儲存層在 Amazon DocumentDB ](db-clusters-understanding.html)中分開，且運算層可以[獨立於儲存體進行擴展](how-it-works.html)。 Amazon DocumentDB  | 
| 隨需新增讀取容量 | 新增執行個體即可橫向擴展叢集。由於儲存體會連接至服務執行所在的執行個體，因此擴展所需的時間取決於需要移至新執行個體或重新平衡的資料量。 | 您可以在叢集中建立最多 15 個 Amazon DocumentDB 複本，以達成 Amazon DocumentDB 叢集的讀取擴展。 [ Amazon DocumentDB ](db-cluster-manage-performance.html#db-cluster-manage-scaling-reads) 不會影響儲存層。 | 
| 從節點故障快速復原 | 叢集具有自動容錯移轉功能，但讓叢集恢復完整強度的時間取決於需要移至新執行個體的資料量。 | Amazon DocumentDB 通常可以在 30 秒內[容錯移轉主要](failover.html)伺服器，並在 8-10 分鐘內將叢集還原至完整強度，無論叢集中的資料量為何。 | 
| 隨著資料成長擴展儲存體 | 對於自我管理叢集，儲存體和 IOs 不會自動擴展。 | Amazon DocumentDB [儲存體和 IOs會自動擴展](db-cluster-manage-performance.html#db-cluster-manage-scaling-storage)。 | 
| 在不影響效能的情況下備份資料 | 備份是由備份服務執行，預設不會啟用。由於儲存和運算不會分開，因此可能會影響效能。 | Amazon DocumentDB 備份預設為啟用，無法關閉。備份由儲存層處理，因此對運算層沒有影響。Amazon DocumentDB 支援[從叢集快照還原](backup_restore-restore_from_snapshot.html)，並[還原至某個時間點](backup_restore-point_in_time_recovery.html)。 | 
| 資料耐久性 | 叢集中最多可以有 3 個資料複本，總共 4 個複本。執行資料服務的每個執行個體都會有作用中的資料複本和 1、2 或 3 個複本。 | Amazon DocumentDB 會維護 6 個資料副本，無論有多少個運算執行個體的寫入規定人數為 4 且持續為 true。儲存層保留 4 個資料副本後，用戶端會收到確認。 | 
| 一致性 | 支援 K/V 操作的立即一致性。Couchbase SDK 會將 K/V 請求路由到包含資料作用中複本的特定執行個體，因此一旦確認更新，用戶端保證會讀取該更新。複寫其他 服務的更新 （索引、搜尋、分析、事件） 最終一致。 | Amazon DocumentDB 複本最終一致。如果需要立即一致性讀取，用戶端可以從主要執行個體讀取。 | 
| 複寫 | 跨資料中心複寫 (XDCR) 提供篩選、主動-被動/主動-主動複寫許多拓撲中的資料。 | [Amazon DocumentDB 全域叢集](global-clusters.html)在 1：many （最多 10 個） 拓撲中提供主動-被動複寫。 | 

## 探索
<a name="discovery"></a>

遷移至 Amazon DocumentDB 需要徹底了解現有的資料庫工作負載。工作負載探索是分析 Couchbase 叢集組態和操作特性的程序，包括資料集、索引和工作負載，以協助確保無縫轉換，並將中斷降至最低。

### 叢集組態
<a name="cluster-configuration"></a>

Couchbase 使用以服務為中心的架構，其中每個功能對應至服務。針對您的 Couchbase 叢集執行下列命令，以判斷正在使用哪些服務 （請參閱[取得節點資訊](https://docs.couchbase.com/server/current/rest-api/rest-node-get-info.html))：

```
curl -v -u <administrator>:<password> \
  http://<ip-address-or-hostname>:<port>/pools/nodes | \
  jq '[.nodes[].services[]] | unique'
```

輸出範例：

```
[
  "backup",
  "cbas",
  "eventing",
  "fts",
  "index",
  "kv",
  "n1ql"
]
```

Couchbase 服務包括下列項目：

#### 資料服務 (kv)
<a name="data-service-kv"></a>

資料服務提供對記憶體和磁碟上資料的讀取/寫入存取權。

Amazon DocumentDB 透過 [MongoDB API](java-crud-operations.html) 支援 JSON 資料的 K/V 操作。

#### 查詢服務 (n1ql)
<a name="query-service-n1ql"></a>

查詢服務支援透過 SQL\$1\$1 查詢 JSON 資料。

Amazon DocumentDB 支援透過 MongoDB API 查詢 JSON 資料。

#### 索引服務 （索引）
<a name="index-service-index"></a>

索引服務會建立和維護資料索引，從而加快查詢速度。

Amazon DocumentDB 支援預設主要索引，並透過 MongoDB API 在 JSON 資料上建立次要索引。

#### 搜尋服務 （英尺）
<a name="search-service-fts"></a>

搜尋服務支援建立索引以進行全文搜尋。

Amazon DocumentDB 的原生全文搜尋功能可讓您透過 MongoDB API[，使用特殊用途文字索引對大型文字資料集執行文字搜尋](text-search.html)。對於進階搜尋使用案例，[Amazon DocumentDB 與 Amazon OpenSearch Service 的零 ETL 整合](https://aws.amazon.com/blogs/big-data/amazon-documentdb-zero-etl-integration-with-amazon-opensearch-service-is-now-available/)可在 Amazon DocumentDB 資料上提供進階搜尋功能，例如模糊搜尋、跨集合搜尋和多語言搜尋。

#### Analytics 服務 (cbas)
<a name="analytics-service-cbas"></a>

分析服務支援近乎即時地分析 JSON 資料。

Amazon DocumentDB 透過 MongoDB API 支援對 JSON 資料進行臨機操作查詢。您也可以[使用在 Amazon EMR 上執行的 Apache Spark，在 Amazon DocumentDB 中對 JSON 資料執行複雜的查詢](https://aws.amazon.com/blogs/database/run-complex-queries-on-massive-amounts-of-data-stored-on-your-amazon-documentdb-clusters-using-apache-spark-running-on-amazon-emr/)。

#### 事件服務 （事件）
<a name="eventing-service-eventing"></a>

事件服務會執行使用者定義的商業邏輯，以回應資料變更。

每次資料隨 Amazon DocumentDB 叢集變更時，Amazon DocumentDB 都會叫用 函數，以自動化事件驅動的工作負載。 [AWS Lambda Amazon DocumentDB ](https://docs.aws.amazon.com/lambda/latest/dg/with-documentdb-tutorial.html)

#### 備份服務 （備份）
<a name="backup-service-backup"></a>

備份服務會排程完整和增量資料備份，以及先前資料備份的合併。

Amazon DocumentDB 會持續將資料備份至 Amazon S3，保留期間為 1–35 天，讓您可以快速還原至備份保留期間內的任何時間點。Amazon DocumentDB 也會擷取資料的自動快照，做為此持續備份程序的一部分。您也可以[使用 管理 Amazon DocumentDB 的備份和還原 AWS Backup。](https://aws.amazon.com/blogs/storage/manage-backup-and-restore-of-amazon-documentdb-with-aws-backup/)

### 操作特性
<a name="operational-characteristics"></a>

使用適用於 [Couchbase 的 Discovery Tool](https://github.com/awslabs/amazon-documentdb-tools/tree/master/migration/discovery-tool-for-couchbase) 取得有關資料集、索引和工作負載的下列資訊。此資訊可協助您調整 Amazon DocumentDB 叢集的大小。

#### 資料集
<a name="data-set"></a>

此工具會擷取下列儲存貯體、範圍和集合資訊：

1. 儲存貯體名稱

1. 儲存貯體類型

1. 範圍名稱

1. 集合名稱

1. 總大小 （位元組）

1. 項目總數

1. 項目大小 （位元組）

#### 索引
<a name="indexes"></a>

此工具會擷取所有儲存貯體的下列索引統計資料和所有索引定義。請注意，主要索引會被排除，因為 Amazon DocumentDB 會自動為每個集合建立主要索引。

1. 儲存貯體名稱

1. 範圍名稱

1. 集合名稱

1. 索引名稱

1. 索引大小 （位元組）

#### 工作負載
<a name="workload"></a>

工具會擷取 K/V 和 N1QL 查詢指標。K/V 指標值會在儲存貯體層級收集，SQL\$1\$1 指標則會在叢集層級收集。

工具命令列選項如下所示：

```
python3 discovery.py \
  --username <source cluster username> \
  --password <source cluster password> \
  --data_node <data node IP address or DNS name> \
  --admin_port <administration http REST port> \
  --kv_zoom <get bucket statistics for specified interval> \
  --tools_path <full path to Couchbase tools> \
  --index_metrics <gather index definitions and SQL++ metrics> \
  --indexer_port <indexer service http REST port> \
  --n1ql_start <start time for sampling> \
  --n1ql_step <sample interval over the sample period>
```

以下為範例命令：

```
python3 discovery.py \
  --username username \
  --password ******** \
  --data_node "http://10.0.0.1" \
  --admin_port 8091 \
  --kv_zoom week \
  --tools_path "/opt/couchbase/bin" \
  --index_metrics true \
  --indexer_port 9102 \
  --n1ql_start -60000 \
  --n1ql_step 1000
```

K/V 指標值將以過去一週每 10 分鐘的樣本為基礎 （請參閱 [HTTP 方法和 URI](https://docs.couchbase.com/server/current/rest-api/rest-bucket-stats.html#http-method-and-uri))。SQL\$1\$1 指標值將以過去 60 秒內每 1 秒的範例為基礎 （請參閱[一般標籤](https://docs.couchbase.com/server/current/rest-api/rest-statistics-single.html#general-labels))。命令的輸出將位於下列檔案中：

**collection-stats.csv** – 儲存貯體、範圍和集合資訊

```
bucket,bucket_type,scope_name,collection_name,total_size,total_items,document_size
beer-sample,membase,_default,_default,2796956,7303,383
gamesim-sample,membase,_default,_default,114275,586,196
pillowfight,membase,_default,_default,1901907769,1000006,1902
travel-sample,membase,inventory,airport,547914,1968,279
travel-sample,membase,inventory,airline,117261,187,628
travel-sample,membase,inventory,route,13402503,24024,558
travel-sample,membase,inventory,landmark,3072746,4495,684
travel-sample,membase,inventory,hotel,4086989,917,4457
...
```

**index-stats.csv** – 索引名稱和大小

```
bucket,scope,collection,index-name,index-size
beer-sample,_default,_default,beer_primary,468144
gamesim-sample,_default,_default,gamesim_primary,87081
travel-sample,inventory,airline,def_inventory_airline_primary,198290
travel-sample,inventory,airport,def_inventory_airport_airportname,513805
travel-sample,inventory,airport,def_inventory_airport_city,487289
travel-sample,inventory,airport,def_inventory_airport_faa,526343
travel-sample,inventory,airport,def_inventory_airport_primary,287475
travel-sample,inventory,hotel,def_inventory_hotel_city,497125
...
```

**kv-stats.csv** – 取得、設定和刪除所有儲存貯體的指標

```
bucket,gets,sets,deletes
beer-sample,0,0,0
gamesim-sample,0,0,0
pillowfight,369,521,194
travel-sample,0,0,0
```

**n1ql-stats.csv** – SQL\$1\$1 選取、刪除和插入叢集的指標

```
selects,deletes,inserts
0,132,87
```

**indexes-<bucket-name>.txt** – 儲存貯體中所有索引的索引定義。請注意，主要索引會被排除，因為 Amazon DocumentDB 會自動為每個集合建立主要索引。

```
CREATE INDEX `def_airportname` ON `travel-sample`(`airportname`)
CREATE INDEX `def_city` ON `travel-sample`(`city`)
CREATE INDEX `def_faa` ON `travel-sample`(`faa`)
CREATE INDEX `def_icao` ON `travel-sample`(`icao`)
CREATE INDEX `def_inventory_airport_city` ON `travel-sample`.`inventory`.`airport`(`city`)
CREATE INDEX `def_inventory_airport_faa` ON `travel-sample`.`inventory`.`airport`(`faa`)
CREATE INDEX `def_inventory_hotel_city` ON `travel-sample`.`inventory`.`hotel`(`city`)
CREATE INDEX `def_inventory_landmark_city` ON `travel-sample`.`inventory`.`landmark`(`city`)
CREATE INDEX `def_sourceairport` ON `travel-sample`(`sourceairport`)
...
```

## 規劃
<a name="planning"></a>

在規劃階段，您將判斷 Amazon DocumentDB 叢集需求，並將 Couchbase 儲存貯體、範圍和集合映射至 Amazon DocumentDB 資料庫和集合。

### Amazon DocumentDB 叢集需求
<a name="amazon-documentdb-cluster-requirements"></a>

使用探索階段中收集的資料來調整 Amazon DocumentDB 叢集的大小。如需[調整 Amazon DocumentDB 叢集大小的詳細資訊](best_practices.html#best_practices-instance_sizing)，請參閱執行個體大小。 Amazon DocumentDB 

### 將儲存貯體、範圍和集合映射至資料庫和集合
<a name="mapping-buckets-scopes-and-collections-to-databases-and-collections"></a>

判斷 Amazon DocumentDB 叢集中將存在的資料庫和集合 (Amazon DocumentDB)。根據資料在 Couchbase 叢集中的組織方式，考慮下列選項。這些並非唯一的選項，而是提供起點供您考慮。

#### Couchbase Server 6.x 或更早版本
<a name="couchbase-6x-or-earlier"></a>

##### Amazon DocumentDB 集合的 Couchbase 儲存貯體
<a name="couchbase-buckets-to-amazon-documentdb-collections"></a>

將每個儲存貯體遷移至不同的 Amazon DocumentDB 集合。在此案例中，Couchbase 文件`id`值將用作 Amazon DocumentDB `_id`值。

![\[Amazon DocumentDB 集合的 Couchbase Server 6.x 或舊版儲存貯體\]](http://docs.aws.amazon.com/zh_tw/documentdb/latest/developerguide/images/buckets-to-collections.png)


#### Couchbase Server 7.0 或更新版本
<a name="couchbase-70-or-later"></a>

##### Amazon DocumentDB 集合的 Couchbase 集合
<a name="couchbase-collections-to-amazon-documentdb-collections"></a>

將每個集合遷移至不同的 Amazon DocumentDB 集合。在此案例中，Couchbase 文件`id`值將用作 Amazon DocumentDB `_id`值。

![\[Amazon DocumentDB 集合的 Couchbase Server 7.0 或更新版本集合\]](http://docs.aws.amazon.com/zh_tw/documentdb/latest/developerguide/images/collections-to-collections.png)


## 移轉
<a name="migration"></a>

### 索引遷移
<a name="index-migration"></a>

遷移至 Amazon DocumentDB 不僅需要傳輸資料，還需要建立索引，以維持查詢效能並最佳化資料庫操作。本節概述將索引遷移至 Amazon DocumentDB 時的詳細step-by-step程序，同時確保相容性和效率。

使用 [Amazon Q](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/chat-with-q.html) 將 SQL\$1\$1 `CREATE INDEX`陳述式轉換為 Amazon DocumentDB `createIndex()`命令。

1. 上傳 Discovery Tool for Couchbase 建立的 **indexes-<bucket name>.txt** 檔案 (s)。

1. 輸入下列提示：

   `Convert the Couchbase CREATE INDEX statements to Amazon DocumentDB createIndex commands`

Amazon Q 將產生同等的 Amazon DocumentDB `createIndex()`命令。請注意，您可能需要根據您將 [Couchbase 儲存貯體、範圍和集合映射至 Amazon DocumentDB 集合](#mapping-buckets-scopes-and-collections-to-databases-and-collections)的方式更新集合名稱。

例如：

**indexes-beer-sample.txt**

```
CREATE INDEX `beerType` ON `beer-sample`(`type`)
CREATE INDEX `code` ON `beer-sample`(`code`) WHERE (`type` = "brewery")
```

範例 Amazon Q 輸出 （摘錄）：

```
db.beerSample.createIndex(
  { "type": 1 },
  {
    "name": "beerType",
    "background": true
  }
)

db.beerSample.createIndex(
  { "code": 1 },
  {
    "name": "code",
    "background": true,
    "partialFilterExpression": { "type": "brewery" }
  }
)
```

如需 Amazon Q 無法轉換的任何索引，請參閱[管理 Amazon DocumentDB 索引](managing-indexes.html)和[索引和索引屬性](mongo-apis.html#mongo-apis-index)以取得詳細資訊。

### 重構程式碼以使用 MongoDB APIs
<a name="refactor-code-to-use-the-mongodb-apis"></a>

用戶端使用 Couchbase SDKs連線至 Couchbase Server。Amazon DocumentDB 用戶端使用 MongoDB 驅動程式連線至 Amazon DocumentDB。MongoDB 驅動程式也支援 Couchbase SDKs支援的所有語言。如需您語言驅動程式的詳細資訊，請參閱 [MongoDB ](https://www.mongodb.com/docs/drivers/) 驅動程式。

由於 Couchbase Server 和 Amazon DocumentDB 之間的 APIs 不同，因此您需要重構程式碼，才能使用適當的 MongoDB APIs。您可以使用 [Amazon Q](https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/chat-with-q.html) 將 K/V API 呼叫和 SQL\$1\$1 查詢轉換為同等的 MongoDB APIs：

1. 上傳原始程式碼檔案 (s)。

1. 輸入下列提示：

   `Convert the Couchbase API code to Amazon DocumentDB API code`

使用 [Hello Couchbase](https://docs.couchbase.com/python-sdk/current/hello-world/start-using-sdk.html#hello-couchbase) Python 程式碼範例，Amazon Q 會產生下列項目 （摘錄）：

```
from datetime import timedelta
from pymongo import MongoClient

# Connection parameters
database_name = "travel-sample"

# Connect to Amazon DocumentDB cluster
client = MongoClient('<Amazon DocumentDB connection string>')

# Get reference to database and collection
db = client['travel-sample']
airline_collection = db['airline']

# upsert document function
def upsert_document(doc):
    print("\nUpsert Result: ")
    try:
        # key will equal: "airline_8091"
        key = doc["type"] + "_" + str(doc["id"])
        doc['_id'] = key # Amazon DocumentDB uses _id as primary key
        result = airline_collection.update_one(
            {'_id': key},
            {'$set': doc},
            upsert=True
        )
        print(f"Modified count: {result.modified_count}")
    except Exception as e:
        print(e)

# get document function
def get_airline_by_key(key):
    print("\nGet Result: ")
    try:
        result = airline_collection.find_one({'_id': key})
        print(result)
    except Exception as e:
        print(e)

# query for document by callsign
def lookup_by_callsign(cs):
    print("\nLookup Result: ")
    try:
        result = airline_collection.find(
            {'callsign': cs},
            {'name': 1, '_id': 0}
        )
        for doc in result:
            print(doc['name'])
    except Exception as e:
        print(e)

# Test document
airline = {
    "type": "airline",
    "id": 8091,
    "callsign": "CBS",
    "iata": None,
    "icao": None,
    "name": "Couchbase Airways",
}

upsert_document(airline)
get_airline_by_key("airline_8091")
lookup_by_callsign("CBS")
```

如需在 Python、Node.js、PHP、Go、Java、C\$1/ 中連線至 Amazon DocumentDB 的範例，請參閱[以程式設計方式連線至 Amazon DocumentDB](connect_programmatically.html)。NET、R 和 Ruby。

### 選取遷移方法
<a name="select-the-migration-approach"></a>

將資料遷移至 Amazon DocumentDB 時，有兩個選項：

1. [離線遷移](#offline-migration)

1. [線上遷移](#online-migration)

#### 離線移轉
<a name="offline-migration"></a>

在下列情況下，請考慮離線遷移：
+ **可接受停機時間：**離線遷移涉及停止對來源資料庫的寫入操作、匯出資料，然後將其匯入 Amazon DocumentDB。此程序會為您的應用程式造成停機時間。如果您的應用程式或工作負載可以容忍這段時間無法使用，離線遷移是可行的選項。
+ **遷移較小的資料集或執行概念驗證：**對於較小的資料集，匯出和匯入程序所需的時間相對較短，使離線遷移成為快速簡單的方法。它也非常適合停機時間較不重要的開發、測試和proof-of-concept環境。
+ **簡易性是優先順序：**離線方法使用 cbexport 和 mongoimport，通常是遷移資料最直接的方法。它可避免線上遷移方法中涉及的變更資料擷取 (CDC) 的複雜性。
+ **不需要複寫正在進行的變更：**如果來源資料庫在遷移期間未主動接收變更，或在遷移過程中擷取和套用這些變更到目標並不重要，則離線方法是適當的。

**Topics**
+ [Couchbase Server 6.x 或更早版本](#couchbase-6x-or-earlier-offline)
+ [Couchbase Server 7.0 或更新版本](#couchbase-70-or-later-offline)

##### Couchbase Server 6.x 或更早版本
<a name="couchbase-6x-or-earlier-offline"></a>

##### Couchbase 儲存貯體到 Amazon DocumentDB 集合
<a name="couchbase-bucket-to-amazon-documentdb-collection-offline"></a>

使用 [cbexport json](https://docs-archive.couchbase.com/server/6.6/tools/cbexport-json.html) 匯出資料，以建立儲存貯體中所有資料的 JSON 傾印。對於 `--format`選項，您可以使用 `lines`或 `list`。

```
cbexport json \
  --cluster <source cluster endpoint> \
  --bucket <bucket name> \
  --format <lines | list> \
  --username <username> \
  --password <password> \
  --output export.json \
  --include-key _id
```

使用 [mongoimport](backup_restore-dump_restore_import_export_data.html#backup_restore-dump_restore_import_export_data-mongoimport) 搭配匯入行或清單的適當選項，將資料匯入 Amazon DocumentDB 集合：

行：

```
mongoimport \
  --db <database> \
  --collection <collection> \
  --uri "<Amazon DocumentDB cluster connection string>" \
  --file export.json
```

清單：

```
mongoimport \
  --db <database> \
  --collection <collection> \
  --uri "<Amazon DocumentDB cluster connection string>" \
  --jsonArray \
  --file export.json
```

##### Couchbase Server 7.0 或更新版本
<a name="couchbase-70-or-later-offline"></a>

若要執行離線遷移，請使用 cbexport 和 mongoimport 工具：

##### 具有預設範圍和預設集合的 Couchbase 儲存貯體
<a name="couchbase-bucket-with-default-scope-and-default-collection-offline"></a>

使用 [cbexport json](https://docs.couchbase.com/server/current/tools/cbexport-json.html) 匯出資料，以建立儲存貯體中所有集合的 JSON 傾印。對於 `--format`選項，您可以使用 `lines`或 `list`。

```
cbexport json \
  --cluster <source cluster endpoint> \
  --bucket <bucket name> \
  --format <lines | list> \
  --username <username> \
  --password <password> \
  --output export.json \
  --include-key _id
```

使用 [mongoimport](backup_restore-dump_restore_import_export_data.html#backup_restore-dump_restore_import_export_data-mongoimport) 搭配匯入行或清單的適當選項，將資料匯入 Amazon DocumentDB 集合：

行：

```
mongoimport \
  --db <database> \
  --collection <collection> \
  --uri "<Amazon DocumentDB cluster connection string>" \
  --file export.json
```

清單：

```
mongoimport \
  --db <database> \
  --collection <collection> \
  --uri "<Amazon DocumentDB cluster connection string>" \
  --jsonArray \
  --file export.json
```

##### Amazon DocumentDB 集合的 Couchbase 集合
<a name="couchbase-collections-to-amazon-documentdb-collections-offline"></a>

使用 [cbexport json](https://docs.couchbase.com/server/current/tools/cbexport-json.html) 匯出資料，以建立每個集合的 JSON 傾印。使用 `--include-data`選項匯出每個集合。對於 `--format`選項，您可以使用 `lines`或 `list`。使用 `--scope-field`和 `--collection-field`選項，將範圍和集合的名稱存放在每個 JSON 文件的指定欄位中。

```
cbexport json \
  --cluster <source cluster endpoint> \
  --bucket <bucket name> \
  --include-data <scope name>.<collection name> \
  --format <lines | list> \
  --username <username> \
  --password <password> \
  --output export.json \
  --include-key _id \
  --scope-field "_scope" \
  --collection-field "_collection"
```

由於 cbexport 將 `_scope`和 `_collection` 欄位新增至每個匯出的文件，因此您可以透過搜尋和取代`sed`、 或任何您偏好的方法，從匯出檔案中的每個文件中移除它們。

使用 [mongoimport](backup_restore-dump_restore_import_export_data.html#backup_restore-dump_restore_import_export_data-mongoimport) 搭配匯入行或清單的適當選項，將每個集合的資料匯入 Amazon DocumentDB 集合：

行：

```
mongoimport \
--db <database> \
--collection <collection> \
--uri "<Amazon DocumentDB cluster connection string>" \
--file export.json
```

清單：

```
mongoimport \
--db <database> \
--collection <collection> \
--uri "<Amazon DocumentDB cluster connection string>" \
--jsonArray \
--file export.json
```

#### 線上遷移
<a name="online-migration"></a>

當您需要將停機時間降至最低，且持續的變更需要近乎即時地複寫至 Amazon DocumentDB 時，請考慮線上遷移。

請參閱[如何從 Couchbase 執行即時遷移至 Amazon DocumentDB](https://github.com/awslabs/amazon-documentdb-tools/tree/master/migration/migration-utility-for-couchbase)，以了解如何執行即時遷移至 Amazon DocumentDB。文件會逐步引導您部署解決方案，以及將儲存貯體即時遷移至 Amazon DocumentDB 叢集。

**Topics**
+ [Couchbase Server 6.x 或更早版本](#couchbase-6x-or-earlier-online)
+ [Couchbase Server 7.0 或更新版本](#couchbase-70-or-later-online)

##### Couchbase Server 6.x 或更早版本
<a name="couchbase-6x-or-earlier-online"></a>

##### Couchbase 儲存貯體到 Amazon DocumentDB 集合
<a name="couchbase-bucket-to-amazon-documentdb-collection-online"></a>

[Couchbase 的遷移公用程式](https://github.com/awslabs/amazon-documentdb-tools/tree/master/migration/migration-utility-for-couchbase)已預先設定為執行 Couchbase 儲存貯體的線上遷移至 Amazon DocumentDB 集合。查看[接收器連接器](https://github.com/awslabs/amazon-documentdb-tools/blob/master/migration/migration-utility-for-couchbase/migration-utility-connectors.yaml)組態， `document.id.strategy` 參數設定為使用訊息金鑰值作為`_id`欄位值 （請參閱[接收器連接器 ID 策略屬性](https://www.mongodb.com/docs/kafka-connector/current/sink-connector/configuration-properties/id-strategy/#std-label-sink-configuration-id-strategy))：

```
ConnectorConfiguration:
  document.id.strategy: 'com.mongodb.kafka.connect.sink.processor.id.strategy.ProvidedInKeyStrategy'
```

##### Couchbase Server 7.0 或更新版本
<a name="couchbase-70-or-later-online"></a>

##### 具有預設範圍和預設集合的 Couchbase 儲存貯體
<a name="couchbase-bucket-with-default-scope-and-default-collection-online"></a>

[Couchbase 的遷移公用程式](https://github.com/awslabs/amazon-documentdb-tools/tree/master/migration/migration-utility-for-couchbase)已預先設定為執行 Couchbase 儲存貯體的線上遷移至 Amazon DocumentDB 集合。查看[接收器連接器](https://github.com/awslabs/amazon-documentdb-tools/blob/master/migration/migration-utility-for-couchbase/migration-utility-connectors.yaml)組態， `document.id.strategy` 參數設定為使用訊息金鑰值作為`_id`欄位值 （請參閱[接收器連接器 ID 策略屬性](https://www.mongodb.com/docs/kafka-connector/current/sink-connector/configuration-properties/id-strategy/#std-label-sink-configuration-id-strategy))：

```
ConnectorConfiguration:
  document.id.strategy: 'com.mongodb.kafka.connect.sink.processor.id.strategy.ProvidedInKeyStrategy'
```

##### Amazon DocumentDB 集合的 Couchbase 集合
<a name="couchbase-collections-to-amazon-documentdb-collections-online"></a>

設定[來源連接器](https://github.com/awslabs/amazon-documentdb-tools/blob/master/migration/migration-utility-for-couchbase/migration-utility-connectors.yaml)，將每個範圍內的每個 Couchbase 集合串流至個別主題 （請參閱[來源組態選項](https://docs.couchbase.com/kafka-connector/current/source-configuration-options.html#couchbase.collections))。例如：

```
ConnectorConfiguration:
  # add couchbase.collections configuration
  couchbase.collections: '<scope 1>.<collection 1>, <scope 1>.<collection 2>, ...'
```

將[接收器連接器](https://github.com/awslabs/amazon-documentdb-tools/blob/master/migration/migration-utility-for-couchbase/migration-utility-connectors.yaml)設定為從每個主題串流到個別的 Amazon DocumentDB 集合 （請參閱[接收器連接器組態屬性](https://github.com/mongodb-labs/mongo-kafka/blob/master/docs/sink.md#sink-connector-configuration-properties))。例如：

```
ConnectorConfiguration:
  # remove collection configuration  
  #collection: 'test'
  
  # modify topics configuration
  topics: '<bucket>.<scope 1>.<collection 1>, <bucket>.<scope 1>.<collection 2>, ...'

  # add topic.override.%s.%s configurations for each topic 
  topic.override.<bucket>.<scope 1>.<collection 1>.collection: '<collection>'
  topic.override.<bucket>.<scope 1>.<collection 2>.collection: '<collection>'
```

## 驗證
<a name="validation"></a>

本節提供詳細的驗證程序，以在遷移至 Amazon DocumentDB 後驗證資料一致性和完整性。無論遷移方法為何，驗證步驟都適用。

**Topics**
+ [確認目標中存在所有集合](#validation-checklist-step-1)
+ [驗證 souce 和目標叢集之間的文件計數](#validation-checklist-step-2)
+ [比較來源和目標叢集之間的文件](#validation-checklist-step-3)

### 確認目標中存在所有集合
<a name="validation-checklist-step-1"></a>

#### Couchbase 來源
<a name="source-verify-collections"></a>

選項 1：查詢工作台

```
SELECT RAW `path`
  FROM system:keyspaces
  WHERE `bucket` = '<bucket>'
```

選項 2：[cbq](https://docs.couchbase.com/server/current/cli/cbq-tool.html) 工具

```
cbq \
  -e <source cluster endpoint> \
  -u <username> \
  -p <password> \
  -q "SELECT RAW `path`
       FROM system:keyspaces
       WHERE `bucket` = '<bucket>'"
```

#### Amazon DocumentDB 目標
<a name="target-verify-collections"></a>

mongosh （請參閱[連線至 Amazon DocumentDB 叢集](connect-ec2-manual.html#manual-connect-ec2.connect-use))：

```
db.getSiblingDB('<database>')
db.getCollectionNames()
```

### 驗證 souce 和目標叢集之間的文件計數
<a name="validation-checklist-step-2"></a>

#### Couchbase 來源
<a name="source-verify-document-count"></a>

##### Couchbase Server 6.x 或更早版本
<a name="source-verify-document-count-couchbase-6x-or-earlier"></a>

選項 1：查詢工作台

```
SELECT COUNT(*)
FROM `<bucket>`
```

選項 2：[cbq](https://docs.couchbase.com/server/current/cli/cbq-tool.html)

```
cbq \
  -e <source cluster endpoint> \
  -u <username> \
  -p <password> \
  -q "SELECT COUNT(*)
       FROM `<bucket:>`"
```

##### Couchbase Server 7.0 或更新版本
<a name="source-verify-document-count-couchbase-70-or-later"></a>

選項 1：查詢工作台

```
SELECT COUNT(*)
FROM `<bucket>`.`<scope>`.`<collection>`
```

選項 2：[cbq](https://docs.couchbase.com/server/current/cli/cbq-tool.html)

```
cbq \
  -e <source cluster endpoint> \
  -u <username> \
  -p <password> \
  -q "SELECT COUNT(*)
       FROM `<bucket:>`.`<scope>`.`<collection>`"
```

#### Amazon DocumentDB 目標
<a name="target-verify-document-count"></a>

mongosh （請參閱[連線至 Amazon DocumentDB 叢集](connect-ec2-manual.html#manual-connect-ec2.connect-use))：

```
db = db.getSiblingDB('<database>')
db.getCollection('<collection>').countDocuments()
```

### 比較來源和目標叢集之間的文件
<a name="validation-checklist-step-3"></a>

#### Couchbase 來源
<a name="source-compare-documents"></a>

##### Couchbase Server 6.x 或更早版本
<a name="source-compare-documents-couchbase-6x-or-earlier"></a>

選項 1：查詢工作台

```
SELECT META().id as _id, *
FROM `<bucket>`
LIMIT 5
```

選項 2：[cbq](https://docs.couchbase.com/server/current/cli/cbq-tool.html)

```
cbq \
  -e <source cluster endpoint> 
  -u <username> \
  -p <password> \
  -q "SELECT META().id as _id, *
       FROM `<bucket>` \
       LIMIT 5"
```

##### Couchbase Server 7.0 或更新版本
<a name="source-compare-documents-couchbase-70-or-later"></a>

選項 1：查詢工作台

```
SELECT COUNT(*)
FROM `<bucket>`.`<scope>`.`<collection>`
```

選項 2：[cbq](https://docs.couchbase.com/server/current/cli/cbq-tool.html)

```
cbq \
  -e <source cluster endpoint> \
  -u <username> \
  -p <password> \
  -q "SELECT COUNT(*)
       FROM `<bucket:>`.`<scope>`.`<collection>`"
```

#### Amazon DocumentDB 目標
<a name="target-compare-documents"></a>

mongosh （請參閱[連線至 Amazon DocumentDB 叢集](connect-ec2-manual.html#manual-connect-ec2.connect-use))：

```
db = db.getSiblingDB('<database>')
db.getCollection('<collection>').find({
  _id: {
    $in: [
      <_id 1>, <_id 2>, <_id 3>, <_id 4>, <_id 5>
    ]
  }
})
```