本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$merge
在 8.0 中推出
Amazon DocumentDB $merge 中的彙總階段用於將上一個管道階段的結果合併到目標集合中。這有助於根據輸入文件的資料,在目標集合中更新或插入文件。
$merge 階段可讓您根據輸入文件與目標集合之間的相符條件執行各種動作,例如:
- Insert new documents - Update existing documents - Delete documents - Fail the operation if there are any conflicts
參數
-
into:(必要) 要合併輸入文件的目標集合名稱。 -
on:(必要) 做為輸入文件與目標集合之間相符條件的欄位 (s)。 -
whenMatched:(選用) 當輸入文件符合目標集合中的現有文件時,要執行的動作。支援的值為:"merge"、"replace"、"keepExisting"和"fail"。 -
whenNotMatched:(選用) 當輸入文件不符合目標集合中的任何文件時,要執行的動作。支援的值為:"insert"和"fail"。
範例 (MongoDB Shell)
下列範例示範如何使用 $merge階段,使用來自輸入管道的新資料來更新users集合。
建立範例文件
db.users.insertMany([ { _id: 1, name: "John Doe", email: "john@example.com" }, { _id: 2, name: "Jane Smith", email: "jane@example.com" } ]); db.inputData.insertMany([ { _id: 1, name: "John Doe", email: "john@example.com", phone: "123-456-7890" }, { _id: 3, name: "Bob Johnson", email: "bob@example.com", phone: "987-654-3210" } ]);
查詢範例
db.inputData.aggregate([ { $merge: { into: "users", on: "_id", whenMatched: "merge", whenNotMatched: "insert" } } ])
輸出
執行$merge管道之後,users集合將包含下列文件:
[
{ _id: 1, name: "John Doe", email: "john@example.com", phone: "123-456-7890" },
{ _id: 2, name: "Jane Smith", email: "jane@example.com" },
{ _id: 3, name: "Bob Johnson", email: "bob@example.com", phone: "987-654-3210" }
]
程式碼範例
若要檢視使用 $merge命令的程式碼範例,請選擇您要使用的語言標籤: