Prakash Thapa
Prakash Thapa

Reputation: 1285

How to compare a field with another in Mongodb aggregation?

I have pipeline many level in, Now I would like to compare two fields like follow:

db.collection.aggregate({ ...},
{$match:{firstfield:{$gte:"$secondfield"}}})

How to write this query?

Upvotes: 1

Views: 817

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

Close but the actual invocation is slightly different:

db.collection.aggregate([
    { "$project": {
        "firstfield": 1,
        "secondfield": 1,
        "difference": { "$gte": [ "$firstfield", "$secondfield" ] }
    }},
    { "$match": { "difference": true } }
])

So a bit different to the $match invocation, the $project ( or possibly $group ) form allow for a true|false value to be returned on the field comparison.

This allows you to filter with the $match phase later in the pipeline in order to "include|exclude" results based on the logical condition that was projected.

Upvotes: 4

Related Questions