Brian Armstrong
Brian Armstrong

Reputation: 19863

Mongoid where greater than sum of two fields

Hi I'm using mongoid (mongodb) to go a greater than criteria:

Account.where(:field1.gt => 10)

But I was wondering if it was possible to do a criteria where the sum of two fields was greater than some number. Maybe something like this (but doesn't seem to work):

Account.where(:'field1 + field2'.gt => 10)

Maybe some embedded javascript is needed? Thanks!

Upvotes: 2

Views: 2239

Answers (2)

Vickash
Vickash

Reputation: 1096

I'd recommend using the Mongoid 3 syntax as suggested by Piotr, but if you want to make this much more performant, at the expense of some storage overhead, you could try something like this:

class Account
  # ...
  field :field1, :type => Integer
  field :field2, :type => Integer
  field :field3, :type => Integer, default -> { field1 + field2 }

  index({ field3: 1 }, { name: "field3" })

  before_save :update_field3

private

  def update_field3
    self.field3 = field1 + field2
  end

end

Then your query would look more like:

Account.where(:field3.gte => 10)

Notice the callback to update field3 when the document changes. Also added an index for it.

Upvotes: 1

Piotr Jakubowski
Piotr Jakubowski

Reputation: 1750

You can use MongoDB's javascript query syntax.

So you can do something like:

Account.collection.find("$where" => '(this.field1 + thist.field2) > 10')

Or in Mongoid 3 the following will work as well

Account.where('(this.field1 + thist.field2) > 10')

As Sammaye mentioned in the comment it introduces the performance penealty since javascript has to be executed for every document individually. If you don't use that query that often then it's ok. But if you do I would recommend adding another field that would be the aggregation of field1 and field2 and then base the query on that field.

Upvotes: 0

Related Questions