$replaceAll - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$replaceAll

5.0 で導入

Amazon DocumentDB の $replaceAll演算子は、フィールド内の指定された文字列パターンのすべての出現を新しい文字列に置き換えるために使用されます。この演算子は、データの正規化、テキストクリーニング、文字列操作などのタスクに役立ちます。

パラメータ

  • input: 置き換える文字列を含むフィールドまたは式。

  • find: 検索して置き換える文字列パターン。

  • replacement: 一致した出現を置き換える文字列。

例 (MongoDB シェル)

次の例は、集約パイプラインで $replaceAll演算子を使用して、文字列「Chocolatier」のすべての出現を「Chocolate Co.」に置き換える方法を示しています。「製品」コレクションのbrandName」フィールド。

サンプルドキュメントを作成する

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()