Project boolean value in aggregation framework

aggregation-framework, mongodb, nosql

Solution

You have to use `$cond`:

db.test.aggregate([
    {
        $match: {id: 123}
    }, 
    {
        $unwind: "$data"
    }, 
    {
        $project: {
            "bool_val": { 
                $cond: [ {$gt: [ "$data.val", 3] }, 1, 0 ]
            }, 
            _id: 0
        }
    } 
]) 

Problem

Is it possible to `project` the boolean value of an operation with MongoDB's aggregation framework? For example, given an input document like so: ``` { "id": 123, "data": [ { "val": 1 }, { "val": 2 }, { "val": 3 }, { "val": 4 }, { "val": 5 } ] } ``` And the operation being `$data.val > 3` I'd like to return: ``` { "result": [ { "bool_val": 0 }, { "bool_val": 0 }, { "bool_val": 0 }, { "bool_val": 1 }, { "bool_val": 1 } ], "ok": 1 } ``` This is what I came up with: ``` db.test.aggregate([{$match: {id: 123}}, {$unwind: "$data"}, {$project: {"bool_val": {"$data.val": {$gt: 3}}, _id: 0}} ]) ``` Which produces the following error: ``` aggregate failed: { "errmsg": "exception: invalid operator '$data.val'", "code": 15999, "ok": 0 } ```

Original source