当被其他变量除时,MongoDB除法返回null [英] MongoDB divide returns null when dividing by other variable
问题描述
我正在尝试计算一些数字,但是在$ divide运算符中使用先前的计算变量时,MongoDB返回null
I am trying to compute some numbers, but MongoDB returns null when using previous computed variable in $divide operator
这是查询:
db.apps.aggregate(
{$project : {
a: {$multiply : [2,2]},
b: {$divide: [5, "$a"]},
c: {$divide: [5, 4]}
}})
为什么"b"在结果中为空:
Why "b" is null in the result:
/* 0 */
{
"result" : [
{
"_id" : ObjectId("5361173d93861f6e5239714e"),
"a" : 4,
"b" : null,
"c" : 1.25
},
{
"_id" : ObjectId("536192c1938652d039fa0051"),
"a" : 4,
"b" : null,
"c" : 1.25
}
],
"ok" : 1
}
感谢Neil的评论,解决方案是拥有第二阶段的$ project
Thanks to Neil comment, the solution is to have second stage $project
db.apps.aggregate(
{$project : {
a: {$multiply : [2,2]},
b: {$divide: [5, "$a"]},
c: {$divide: [5, 4]}
}},
{$project : {
a: 1, c:1,
b: {$divide: [5, "$a"]},
}}
)
推荐答案
$project
步骤中的变量始终是该步骤的 input 文档的字段.您还不能访问在同一步骤中计算出的任何值.但是您可以在随后的$ project步骤中访问任何计算所得的值.因此,您可以将计算分为两个$ project步骤,如下所示:
The variables in a $project
step are always the fields of the input document of that step. You can not yet access any values computed in the same step. But you can access any computed values in a following $project step. So you can break your computation into two $project-steps like this:
db.apps.aggregate(
[
{ $project : {
a: { $multiply : [2, 2] }
}
},
{ $project : {
a: 1,
b: { $divide: [5, "$a"] }
}
}
]
);
这篇关于当被其他变量除时,MongoDB除法返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!