本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$group
Amazon DocumentDB 中的$group聚合阶段允许您按指定的表达式对文档进行分组,并对分组的数据执行各种累积操作。这对于诸如根据分组数据计算总计、平均值或其他统计数据之类的任务非常有用。
参数
示例(MongoDB 外壳)
以下示例按城市对客户进行分组,并计算每个城市的总订单金额。
创建示例文档
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 }
]
代码示例
要查看使用该$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()