CSharpAtl
CSharpAtl

Reputation: 7512

How to compare 2 properties that are in a mongo document?

I have documents in mongo and they have properties of {number1: <some number>, number2: <some other number>} I want to do a query where number1 < number2 without using the $where operator (as it is not performant). This query is part of an aggregate pipeline.

Upvotes: 3

Views: 1693

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50406

If you need to do this in an aggregation pipeline then use $redact:

{ "$redact": {
    "$cond": {
        "if": {
            "$lt": [ "$number1", "$number2" ]
        },
        "then": "$$KEEP",
        "else": "$$PRUNE"
    }
}}

It allows logical comparison and removal in a single stage. If you have an older MongoDB than 2.6 then you can $project the logical result and $match to filter these out instead.

{ "$project": {
    "someField": 1,
    "test": { "$lt": [ "$number1", "$number2" ] }
}},
{ "$match": { "test": true } }

Upvotes: 5

Related Questions