Question

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

)
Was it helpful?

Solution

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

OTHER TIPS

now you can use let. Like that:

db.apps.aggregate([{
    $project: {
        b: {
            $let: {
                vars: {
                    "a": {$multiply: [2,2]}
                },
                in: {$divide: [5, "$$a"]}
            }
        }
    }}
]);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top