mongodb - MongoDB 对数组中的元素进行分组
问题描述
对于每个product_id,我想要所有订单中的价格总和以及我想要实现的另一个结果是同一数组中具有相同id的产品的价格总和。
\\orders collection:
{
order_id: 123,
customer_id: 1,
order_items: [{product_id:1, price: 2}, {product: 4, price: 8}, {product_id:1, price: 2}]
},
{
order_id: 124,
customer_id: 5,
order_items: [{product_id:5, price: 7}, {product: 4, price: 8}]
}
我想要的第一个结果:
{product_id: 1, tot_price: 4},
{product_id: 4, tot_price: 16},
{product_id: 5, tot_price: 7}
第二个结果:
{order_id:123,
product_tot: [{product_id:1, tot_price: 4}, {product: 4, tot_price: 8}]},
{order_id:124,
product_tot: [{product_id:5, tot_price: 7}, {product: 4, tot_price: 8}},
解决方案
尝试以下查询:
第一个结果:
db.collection.aggregate([
{
$unwind: {
path: "$order_items",
preserveNullAndEmptyArrays: true
}
},
{
$group: {
_id: "$order_items.product_id",
tot_price: {
$sum: "$order_items.price"
}
}
},
{
$project: {
_id: 0,
product_id: "$_id",
tot_price: 1
}
}
])
对于第二个结果:
db.collection.aggregate([
{
$unwind: {
path: "$order_items",
preserveNullAndEmptyArrays: true
}
},
{
$group: {
_id: {
order_id: "$order_id",
product_id: "$order_items.product_id"
},
tot_price: {
$sum: "$order_items.price"
}
}
},
{
$project: {
_id: 0,
order_id: "$_id.order_id",
product_id: "$_id.product_id",
tot_price: "$tot_price"
}
},
{
$group: {
_id: "$order_id",
product_tot: {
$push: {
product_id: "$product_id",
tot_price: "$tot_price"
}
}
}
},
{
$project: {
_id: 0,
order_id: "$_id",
product_tot: 1
}
}
])
推荐阅读
- objective-c - Property cannot be marked @objc because its type cannot be represented in Objective-C
- javascript - Angular 5:“AppModule”未找到 NgModule 元数据中的错误
- javascript - Jest 测试失败
- java - 我可以将“str”.equals(obj) 与 toString 实现一起使用吗?
- php - PHP中图像中的随机线生成
- c# - 具有相同参数子集的参数集的 Powershell C# cmdlet
- python - 从 Python 打印 Powerpoint 幻灯片
- json - 在 python 中创建一个没有 Flask 的 REST API
- python - 如何使用 plotly 和 cufflinks 绘制多轴?
- python - SyntaxError print(*args, **kwargs)