gpt4 book ai didi

MongoDb $addFields inside arrays $multiply 数组中的两个值

转载 作者:可可西里 更新时间:2023-11-01 10:00:12 25 4
gpt4 key购买 nike

MongoDb 版本 3.4.4

如何为数组快照中的每个对象聚合一个新键“total”,其值是“course”和“quantity”的乘积。

示例文档:

{
cur: "EUR",
snapshot: [
{
id: "24352345",
course: 58.12,
quantity: 13
},
{
id: "34552345",
course: 18.12,
quantity: 63
}
]
}

期望的结果:

{
cur: "EUR",
snapshot: [
{
id: "24352345",
course: 58.12,
quantity: 13,
total: 755.56
},
{
id: "34552345",
course: 18.12,
quantity: 63,
total: 1141.56
}
]
}

第一次尝试:

db.mycoll.aggregate([{
$addFields: {
"snapshot.total": {
$multiply:["$snapshot.quantity", "$snapshot.course"]
}
}
}])

"errmsg": "$multiply 只支持数值类型,不支持数组"

第二次尝试:

db.mycoll.aggregate( [ 
{ "$addFields": {
"snapshot.total": {
"$map": {
"input": "$snapshot",
"as": "row",
"in": { "$multiply": [
{ "$ifNull": [ "$$row.quantity", 0 ] },
{ "$ifNull": [ "$$row.course", 0 ] }
]}
}
}
}}
])

'total' 的不需要的值是一个包含所有对象总和的数组:

{
cur: "EUR",
snapshot: [
{
id: "24352345",
course: 58.12,
quantity: 13,
total: [
755.56,
1141.56
]
},
{
id: "34552345",
course: 18.12,
quantity: 63,
total: [
755.56,
1141.56
]
}
]
}

最佳答案

使用 $map operator 修改您的第二次尝试将整个快照嵌入文档与其字段映射为

db.mycoll.aggregate([
{
"$addFields": {
"snapshot": {
"$map": {
"input": "$snapshot",
"as": "row",
"in": {
"id": "$$row.id",
"course": "$$row.course",
"quantity": "$$row.quantity",
"total": { "$multiply": [
{ "$ifNull": [ "$$row.quantity", 0 ] },
{ "$ifNull": [ "$$row.course", 0 ] }
]}
}
}
}
}
}
])

关于MongoDb $addFields inside arrays $multiply 数组中的两个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43951945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com