Search code examples
mongodbmongodb-queryaggregation-frameworkmongodb-aggregation

$match on sum of two fields


In the mongodb aggregation pipeline how do I match on the sum of two fields being non zero? So I can say the following to give me all the documents where startPos is greater than 10

db.strategy.aggregate(
    [
        {
            $match: {
             "startPos": {"$gt" :10}
            }
        },

    ]
);

But how do I say something like:

db.strategy.aggregate(
    [
        {
            $match: {
             {"$subtract":["endPos","startPos"]}: {"$gt" :10} <== Clearly not legal
            }
        },

    ]
);

Solution

  • You can use redact to achieve this.

    db.strategy.aggregate([
                    {"$redact" : 
                        { "$cond" : { 
                            if : { $gt: [ {"$subtract":["$endPos","$startPos"] }, 10] }, 
                            then: "$$KEEP", 
                            else: "$$PRUNE" 
                            } 
                        }         
                    }
                ] );