

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

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

Amazon DocumentDB の `$out`演算子は、集約パイプラインの結果を指定されたコレクションに書き込むために使用されます。

`$out` はパイプラインの最後のステージである必要があります。

**パラメータ**
+ `output_collection`: 集計結果を書き込む出力コレクションの名前。

**注**: コレクションが既に存在する場合、集約ステージの結果に置き換えられます。

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

次の例は、Amazon DocumentDB の `$out`演算子を使用して、集約パイプラインの結果を新しいコレクションに書き込む方法を示しています。

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

```
db.products.insertMany([
  { _id: 1, name: "Wireless Headphones", category: "Electronics", price: 100.0 },
  { _id: 2, name: "Smartphone", category: "Electronics", price: 200.0 },
  { _id: 3, name: "JavaScript Guide", category: "Books", price: 50.0 },
  { _id: 4, name: "Database Design Handbook", category: "Books", price: 75.0 }
]);
```

**クエリの例**

```
db.products.aggregate([
  { $group: { _id: "$category", totalPrice: { $sum: "$price" } } },
  { $out: "product_categories" }
])
```

**出力**

なし (結果は出力コレクションに書き込まれます）。

集約パイプラインは製品をカテゴリ別にグループ化し、各カテゴリの項目の合計価格を計算します。`$out` 演算子は、「product\$1categories」という名前の新しいコレクションに結果を書き込みます。

**出力コレクションで結果を表示するには:**

```
db.product_categories.find()
[
{ "_id" : "Books", "totalPrice" : 125 },
{ "_id" : "Electronics", "totalPrice" : 300 }
]
```

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

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

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

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

async function demo_out_operator() {
  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 products = db.collection('products');

  // Execute aggregation with $out - results are stored in 'product_categories' collection
  await products.aggregate([
    { $group: { _id: "$category", totalPrice: { $sum: "$price" } } },
    { $out: "product_categories" }
  ]).toArray();

  // Retrieve the results from the output collection (limited to 20 records)
  const productCategories = db.collection('product_categories');
  const results = await productCategories.find({}).limit(20).toArray();
  
  console.log('Results stored in product_categories collection:', results);
  await client.close();
}

demo_out_operator();
```

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

```
from pymongo import MongoClient

def demo_out_operator():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    products = db['products']

    # Execute aggregation with $out - results are stored in 'product_categories' collection
    list(products.aggregate([
        { '$group': { '_id': '$category', 'totalPrice': { '$sum': '$price' } } },
        { '$out': 'product_categories' }
    ]))

    # Retrieve the results from the output collection (limited to 20 records)
    product_categories = db['product_categories']
    results = list(product_categories.find({}).limit(20))
    
    print('Results stored in product_categories collection:', results)
    client.close()

demo_out_operator()
```

------