

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

# \$1replaceWith
<a name="replaceWith"></a>

バージョン 8.0 の新機能

Elastic クラスターではサポートされていません。

Amazon DocumentDB の`$replaceWith`集約ステージは、入力ドキュメントを新しいドキュメントに置き換えるために使用されます。\$1id フィールドを含む入力ドキュメントのすべての既存のフィールドは、新しいドキュメントに置き換えられます。 `$replaceWith`は、ドキュメントをフラット化したり、埋め込みドキュメントを最上位レベルに昇格させたりするためによく使用されます。

**パラメータ**
+ `<replacement>` (必須): 既存のドキュメントを置き換える新しいドキュメント。

## 例 (MongoDB シェル)
<a name="replaceWith-examples"></a>

次の例は、 `$replaceWith`演算子を使用して Amazon DocumentDB コレクション内の既存のドキュメントを置き換える方法を示しています。

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

```
db.restaurants.insertMany([
  {
    "restaurantId": "REST-0Y9GL0",
    "name": "Biryani Adda",
    "cuisine": "Indian",
    "ratings": [ 3, 4, 3, 2, 2, 4, 1, 5, 5, 5 ]
  },
  {
    "restaurantId": "REST-8L2PX9",
    "name": "The Burger Spot",
    "cuisine": "American",
    "ratings": [ 2, 3, 4, 5, 3, 1, 1, 2, 4 ]
  }
]);
```

**クエリの例**

```
db.restaurants.aggregate([
  { $replaceWith: {
      name: "$name",
      cuisine: "$cuisine",
      rating: { $avg: "$ratings" }
    }
  }
]);
```

**出力**

```
[
  {
    name: 'Biryani Adda',
    cuisine: 'Indian',
    rating: 3.4
  },
  {
    name: 'The Burger Spot',
    cuisine: 'American',
    rating: 2.7777777777777777
  }
]
```

## コードの例
<a name="replaceWith-code"></a>

`$replaceWith` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

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

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

async function replaceDoc() {
  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('restaurants');

  const result = await collection.aggregate([
    { $replaceWith: {
        name: "description_index",
        cuisine: 2,
        rating: { $avg: "$ratings" }
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

replaceDoc();
```

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

```
from pymongo import MongoClient


def replace_document():
    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.restaurants

    result = list(collection.aggregate([
        {
            '$replaceWith': {
                'name': "$name",
                'cuisine': "$cuisine",
                'rating': { '$avg': "$ratings"}
            }
        }
    ]))

    print(result)
    client.close()

replace_document()
```

------