gpt4 book ai didi

MongoDB:$divide 和 $multiply 出错

转载 作者:IT老高 更新时间:2023-10-28 13:18:57 27 4
gpt4 key购买 nike

我正在创建一个 MongoDB 聚合管道,但我被困在这个阶段:

        $group: {
_id: {checkType: "$_id.checkType", resultCode: "$_id.resultCode"},
count: { $sum: "$count" },
ctv: { $sum: "$ctv" },
perc:{$multiply:[{$divide:["$ctv","$count"]},100]},
weight: { $divide: [ "$ctv", "$count"] },
details: { $push: "$$ROOT" }
}

它给出错误“$multiply 累加器是一元运算符”。同样,如果我用 $multiply 删除该行,我会在下一行得到“$divide 累加器是一元运算符”。我在网上找不到这个错误的描述。我的语法有什么问题?

最佳答案

arithmetic operators不能用作 $group accumulators .将它们移至另一个 $project 流水线阶段为:

db.collection.aggregate([
{ "$group": {
"_id": { "checkType": "$_id.checkType", "resultCode": "$_id.resultCode" },
"count": { "$sum": "$count" },
"ctv": { "$sum": "$ctv" },
"details": { "$push": "$$ROOT" }
} },
{ "$project": {
"count": 1,
"details": 1,
"ctv": 1,
"perc": { "$multiply": [ { "$divide": ["$ctv","$count"] }, 100 ] },
"weight": { "$divide": ["$ctv", "$count"] },
} }
])

如果使用 MongoDB 3.4 及更高版本,请使用 $addFields 而不是 $project

db.collection.aggregate([
{ "$group": {
"_id": { "checkType": "$_id.checkType", "resultCode": "$_id.resultCode" },
"count": { "$sum": "$count" },
"ctv": { "$sum": "$ctv" },
"details": { "$push": "$$ROOT" }
} },
{ "$addFields": {
"perc": { "$multiply": [ { "$divide": ["$ctv","$count"] }, 100 ] },
"weight": { "$divide": ["$ctv", "$count"] },
} }
])

关于MongoDB:$divide 和 $multiply 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43341863/

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