superluminary
superluminary

Reputation: 49182

Is it possible to find by expression using the mongo find function?

Say I have data like this:

{
  a: 2,
  b: 1
}

I want to find all the values where a is greater than b.

I can obviously do this using the aggregate pipeline, or using $where, but can I do it using the plain old find function? It feels like it ought to be possible to do this, as I would in the aggregate pipeline:

db.collection.find({
  a: {
    '$gt': '$b'
  }
})

(this doesn't work)

Is this not supported, and if not, is this by design, philosophy or omission? Alternately, am I just being an idiot?

Upvotes: 0

Views: 129

Answers (2)

chridam
chridam

Reputation: 103375

I don't think that MongoDB yet supports expressions that accommodate comparison between two or more fields other than the $where expression or the aggregation framework which uses the same query language as regular find.

The best you could do is store in your document a denormalized flag, like isGreater that stores the boolean (a - b > 0) which you can then query with the find()

db.collection.find({"isGreater": true})

There is a similar JIRA ticket for this here SERVER-7623 which is planned but not scheduled.

Upvotes: 1

Sede
Sede

Reputation: 61235

You can use the $redact operator.

db.collection.aggregate(
    [
        { "$redact": {
            "$cond": {
                if: { "$gt": [ "$a", "$b" ] }, 
                then: "$$KEEP", 
                else: "$$PRUNE"
            }
          }
        }
    ]
)

Upvotes: 1

Related Questions