

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# \$1 GantiSatu
<a name="replaceOne"></a>

Diperkenalkan pada 5.0

`$replaceOne`Operator di Amazon DocumentDB adalah operator ekspresi string yang digunakan dalam pipeline agregasi untuk menggantikan kemunculan pertama substring tertentu dalam string dengan string pengganti. Operator ini peka huruf besar/kecil dan hanya menggantikan kecocokan pertama yang ditemukan.

**Parameter**
+ `input`: String (bidang) untuk melakukan pencarian.
+ `find`: String untuk mencari di dalam input.
+ `replacement`: String untuk menggantikan kemunculan pertama dari temuan di input (field).

## Contoh (MongoDB Shell)
<a name="replaceOne-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$replaceOne` operator dalam pipeline agregasi untuk mengganti substring dalam nama produk.

**Buat dokumen sampel**

```
db.products.insertMany([
  { "_id":1, "productId": "PROD-0Y9GL0", "name": "Gordon's Extra Creamy Milk Chocolate - Pack of 4", "category": "Confectionery", "price": 24.99 },
  { "_id":2, "productId": "PROD-Y2E9H5", "name": "Nutrition Co. - Original Corn Flakes Cereal", "category": "Breakfast Cereals", "price": 8.50 },
  { "_id":3, "productId": "PROD-Z3F8K2", "name": "Gordon's Dark Chocolate (90% Cocoa) Pack - Pack of 4", "category": "Confectionery", "price": 28.99 }
]);
```

**Contoh agregasi**

```
db.products.aggregate([
  {
    $addFields: {
      standardizedName: {
        $replaceOne: {
          input: "$name",
          find: "Pack",
          replacement: "Package"
        }
      }
    }
  }
]);
```

**Keluaran**

Output menunjukkan bahwa hanya kemunculan pertama “Pack” di setiap nama produk diganti dengan “Package”.

```
[
  {
    _id: 1,
    productId: 'PROD-0Y9GL0',
    name: "Gordon's Extra Creamy Milk Chocolate - Pack of 4",
    category: 'Confectionery',
    price: 24.99,
    standardizedName: "Gordon's Extra Creamy Milk Chocolate - Package of 4"
  },
  {
    _id: 2,
    productId: 'PROD-Y2E9H5',
    name: 'Nutrition Co. - Original Corn Flakes Cereal',
    category: 'Breakfast Cereals',
    price: 8.5,
    standardizedName: 'Nutrition Co. - Original Corn Flakes Cereal'
  },
  {
    _id: 3,
    productId: 'PROD-Z3F8K2',
    name: "Gordon's Dark Chocolate (90% Cocoa) Pack - Pack of 4",
    category: 'Confectionery',
    price: 28.99,
    standardizedName: "Gordon's Dark Chocolate (90% Cocoa) Package - Pack of 4"
  }
```

## Contoh kode
<a name="replaceOne-code"></a>

Untuk melihat contoh kode untuk menggunakan `$replaceOne` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function replaceOne() {
  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 pipeline = [
    {
      $addFields: {
        standardizedName: {
          $replaceOne: {
            input: '$name',
            find: 'Pack',
            replacement: 'Package'
          }
        }
      }
    }
  ];

  const result = await collection.aggregate(pipeline).toArray();
  console.log(result);

  await client.close();
}

replaceOne();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def replaceOne():
    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']

    pipeline = [
        {
            '$addFields': {
                'standardizedName': {
                    '$replaceOne': {
                        'input': '$name',
                        'find': 'Pack',
                        'replacement': 'Package'
                    }
                }
            }
        }
    ]

    result = list(collection.aggregate(pipeline))
    print(result)

    client.close()

replaceOne()
```

------