我正在尝试在 MongoDB 中进行聚合。
我收藏了一些元素。每个项目都有一个数组 rows
,rows
中的每个对象都有字段 quantity
和 price
。
我想乘以数量
和价格
,但我不知道如何正确指定字段。
我试过了
const pipeline = [
{
$group: {
_id: {
number: '$number',
},
total: {
$sum: {
$multiply: [
'$rows.quantity',
'$rows.price'
]
}
},
}
}
];
但是它说 $multiply
只支持数字类型而不支持数组。
所以好像没理解$rows.quantity
是数组中每个对象中的数值类型字段quantity
我想我可能应该使用 $each
或其他东西来遍历数组中的对象。
来自 Using multiply aggregation with MongoDB我看到我正确指定了字段;然而,在那个例子中它是一个嵌套对象而不是数组,所以也许我必须使用 https://docs.mongodb.org/v3.0/reference/operator/aggregation/unwind/ ?
示例文档
{
number: 2,
rows: [
{
quantity: 10,
price: 312
},
{
quantity: 10,
price: 312
},
{
quantity: 10,
price: 312
},
]
}
最佳答案
使用 .aggregate()
方法。
从版本 3.2 开始,您可以使用 $sum
$project
中的累加器运算符阶段计算并返回数量*价格
数组的总和。当然,要获得数组,您需要使用 $map
运算符(operator)。 $ifNull
运算符计算“数量”和“价格”的值,如果它们的计算结果为空值,则返回 0
。管道的最后阶段是 $group
在此阶段,您按“数字”对文档进行分组并返回每个组的“总数”。
db.collection.aggregate([
{ "$project": {
"number": 1,
"total": {
"$sum": {
"$map": {
"input": "$rows",
"as": "row",
"in": { "$multiply": [
{ "$ifNull": [ "$$row.quantity", 0 ] },
{ "$ifNull": [ "$$row.price", 0 ] }
]}
}
}
}
}},
{ "$group": {
"_id": "$number",
"total": { "$sum": "$total" }
}}
])
如果您使用的不是 3.2 版,则需要在 $project
阶段之前使用 $unwind
对“行”数组进行非规范化运营商。
db.collection.aggregate([
{ "$unwind": "$rows" },
{ "$project": {
"number": 1,
"value": { "$multiply": [
{ "$ifNull": [ "$rows.quantity", 0 ] },
{ "$ifNull": [ "$rows.price", 0 ] }
]}
}},
{ "$group": {
"_id": "$number",
"total": { "$sum": "$value" }
}}
])
关于mongodb - 在 MongoDB 聚合中对嵌套字段使用 $multiply,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556321/