$replaceAll - Amazon DocumentDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

$replaceAll

在 5.0 中引入

Amazon DocumentDB 中的$replaceAll运算符用于将字段中所有出现的指定字符串模式替换为新字符串。此运算符可用于数据标准化、文本清理和字符串操作等任务。

参数

  • input:包含要替换的字符串的字段或表达式。

  • find:要搜索和替换的字符串模式。

  • replacement: 用于替换匹配匹配项的字符串。

示例(MongoDB 外壳)

以下示例演示了如何在聚合管道中使用$replaceAll运算符将所有出现的字符串 “Chocolatier” 替换为 “Chocolatier Co.” 在 “产品” 系列的 “品牌名称” 字段中。

创建示例文档

db.products.insertMany([ { "_id": 1, "productId": "PROD-0Y9GL0", "brandName": "Gordon's Chocolatier", "category": "CPG", "rating": { "average": 4.8 } }, { "_id": 2, "productId": "PROD-1X2YZ3", "brandName": "Premium Chocolatier", "category": "CPG", "rating": { "average": 4.5 } }, { "_id": 3, "productId": "PROD-Y2E9H5", "name": "Nutrition Co. - Original Corn Flakes Cereal", "category": "Breakfast Cereals", "price": 8.5 } ]);

查询示例

db.products.aggregate([ { $addFields: { "brandName": { $replaceAll: { input: "$brandName", find: "Chocolatier", replacement: "Chocolate Co." } } } } ])

输出

[ { _id: 1, productId: 'PROD-0Y9GL0', brandName: "Gordon's Chocolate Co.", category: 'CPG', rating: { average: 4.8 } }, { _id: 2, productId: 'PROD-1X2YZ3', brandName: 'Premium Chocolate Co.', category: 'CPG', rating: { average: 4.5 } }, { _id: 3, productId: 'PROD-Y2E9H5', name: 'Nutrition Co. - Original Corn Flakes Cereal', category: 'Breakfast Cereals', price: 8.5, brandName: null } ]

代码示例

要查看使用该$replaceAll命令的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function replaceAll() { 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'); const collection = db.collection('products'); const results = await collection.aggregate([ { $addFields: { "brandName": { $replaceAll: { input: "$brandName", find: "Chocolatier", replacement: "Chocolate Co." } } } } ]).toArray(); console.log(results); await client.close(); } replaceAll();
Python
from pymongo import MongoClient def replace_all(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client.test collection = db.products results = list(collection.aggregate([ { "$addFields": { "brandName": { "$replaceAll": { "input": "$brandName", "find": "Chocolatier", "replacement": "Chocolate Co." } } } } ])) print(results) client.close() replace_all()