merge - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

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:(必填)用作输入文档和目标集合之间匹配条件的字段。

  • whenMatched:(可选)当输入文档与目标集合中的现有文档相匹配时要执行的操作。支持的值为:"merge""replace""keepExisting""fail"

  • whenNotMatched:(可选)当输入文档与目标集合中的任何文档都不匹配时要执行的操作。支持的值为:"insert""fail"

示例(MongoDB 外壳)

以下示例演示如何使用$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命令的代码示例,请选择要使用的语言的选项卡:

Node.js

以下是在 Node.js 应用程序中使用 $merge 运算符的示例:

const { MongoClient } = require('mongodb'); async function example() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); await db.collection('inputData').aggregate([ { $merge: { into: 'users', on: '_id', whenMatched: 'merge', whenNotMatched: 'insert' } } ]).toArray(); const users = await db.collection('users').find({}).toArray(); console.log(users); await client.close(); } example();
Python

以下是在 Python 应用程序中使用 $merge 运算符的示例:

from pymongo import MongoClient def example(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] # Assumes collections 'users' and 'inputData' already exist with sample data db.inputData.aggregate([ { '$merge': { 'into': 'users', 'on': '_id', 'whenMatched': 'merge', 'whenNotMatched': 'insert' } } ]) users = list(db.users.find({})) print(users) client.close() example()