MongoDB divide returns null when dividing by other variable

最后都变了- 提交于 2020-01-30 13:13:09

问题


I am trying to compute some numbers, but MongoDB returns null when using previous computed variable in $divide operator

This is the query:

db.apps.aggregate(

{$project : {
    a: {$multiply : [2,2]},
    b: {$divide: [5, "$a"]},
    c: {$divide: [5, 4]}

}})

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
}

EDIT: 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"]},   
}}

)

回答1:


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"] }   
            }
        }
    ]
);


来源:https://stackoverflow.com/questions/23676463/mongodb-divide-returns-null-when-dividing-by-other-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!