

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

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

Amazon DocumentDB の`$group`集約ステージでは、指定された式でドキュメントをグループ化し、グループ化されたデータに対してさまざまな累積オペレーションを実行できます。これは、グループ化されたデータに基づいて合計、平均、またはその他の統計を計算するなどのタスクに役立ちます。

**パラメータ**
+ `_id`: 入力ドキュメントをグループ化する式を指定します。これは、フィールド名、計算式、またはその両方の組み合わせです。
+ `accumulator expressions`: (オプション) グループ化されたデータに適用する必要がある 1 つ以上のアキュムレータ式。これらの式は、上記のアキュムレータ演算子を使用します。

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

次の例では、顧客を都市別にグループ化し、各都市の合計注文額を計算します。

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

```
db.customers.insertMany([
  { name: "John Doe", city: "New York", orders: [{ amount: 100 }, { amount: 200 }] },
  { name: "Jane Smith", city: "Los Angeles", orders: [{ amount: 150 }, { amount: 300 }] },
  { name: "Bob Johnson", city: "New York", orders: [{ amount: 75 }, { amount: 125 }] },
  { name: "Samantha Lee", city: "Chicago", orders: [{ amount: 50 }, { amount: 100 }] }
]);
```

**クエリの例**

```
db.customers.aggregate([
  {
    $group: {
      _id: "$city",
      totalOrders: { $sum: { $sum: "$orders.amount" } }
    }
  }
]);
```

**出力**

```
[
  { _id: 'Chicago', totalOrders: 150 },
  { _id: 'Los Angeles', totalOrders: 450 },
  { _id: 'New York', totalOrders: 500 }
]
```

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

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

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

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

async function groupByCity() {
  const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
  const client = new MongoClient(uri);

  try {
    await client.connect();
    const db = client.db('test');
    const result = await db.collection('customers').aggregate([
      { $unwind: '$orders' },
      {
        $group: {
          _id: '$city',
          totalOrders: { $sum: '$orders.amount' }
        }
      }
    ]).toArray();

    console.log(result);
  } catch (err) {
    console.error('Error during aggregation:', err);
  } finally {
    await client.close();
  }
}

groupByCity();
```

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

```
from pymongo import MongoClient

def group_by_city():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    
    try:
        db = client.test
        result = list(db.customers.aggregate([
            {'$unwind': '$orders'},
            {
                '$group': {
                    '_id': '$city',
                    'totalOrders': {'$sum': '$orders.amount'}
                }
            }
        ]))
        print(result)
    except Exception as e:
        print(f"Error during aggregation: {e}")
    finally:
        client.close()

group_by_city()
```

------