[Solved] MongoDB query condition including SUM


The $redact operator of the aggregation framework is your best option:

db.collection.aggregate([
    { "$redact": {
        "$cond": {
            "if": { "$lt": [ { "$add": [ "$b", "$c" ] }, 5 ] },
            "then": "$$KEEP",
            "else": "$$PRUNE"
        }
    }},
    { "$project": { "_id": 0, "a": 1 } }
])

The logical condition is made via $lt on the math expression of $add in order to determine which items to keep.

The $project selects the fields.

The alternate is $where which uses JavaScript evalution. Not as effective due to the JavaScript translation required ( the following is a shell shortcut for $where ):

db.collection.find(
  function() {
    return ( this.b + this.c ) < 5;
  },
  { "_id": 0, "a": 1 }
);

Or:

db.collection.find(
    { "$where": "return ( this.b + this.c ) < 5;" },
    { "_id": 0, "a": 1 }
);

Which is basically the same thing.

Native operators are more performant than JavaScript evalutation.

solved MongoDB query condition including SUM