0

I have a mongo collection which has documents with two fields "fieldA" and "fieldB", which are timestamps and I need to get all the documents which are "(fieldB-fieldA)/6000 > 2"... So I was looking for some function in order to do this...

I saw in some posts the function "$subtract" but that seems is in mongo 2.1.x and currently I'm using 2.0.x (it's the stable), any idea how to do this with 2.0.x? or Do I need to create a new field? or Can I only do it in the application side?

btw, I'm using the ruby mongo driver...

markos
  • 65
  • 2
  • 8

1 Answers1

1

You can use the $where operator to specify query expressions as Javascript. In the shell:

db.myCollection.find( { $where: "(this.fieldB - this.fieldA)/6000 > 2" } );

You should note, however, that Javascript execution can be very slow. If this is a one time query, $where may be an ok solution. Otherwise, storing the result of the equation in a separate field is the best way to ensure that queries are timely.

Additional information on the $where operator: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-JavascriptExpressionsand%7B%7B%24where%7D%7D

Jenna
  • 2,386
  • 17
  • 10
  • awesome, yeah, it worked!... And yeah, I noticed that it's quite slow, however it's an acceptable time waiting at least for me... – markos Jun 14 '12 at 21:10