2

I am using ReactiveMongo, I want to create a query that performs like query with numbers (BigDecimal) in MongoDB. For eg: whole number like 4321.3456 should be matched by 4321.34.

The following 2 queries work on MongoShell to achieve this:

 db.employee.find({"$where":"/^4321.34.*/.test(this.salary)"})

 db.collection.find({ 
    "$where": function() { 
        return Math.round(this.salary * 100)/ 100 === 1.12; 
    }
})

But, I couldn't find a way to perform this query using ReactiveMongo.

How can I execute such queries using ReactiveMongo ?

UPDATE

I have tried following query

 val filter=Json.obj("$where" -> """/^4321.34.*/.test(this.salary)"""))
 collection.find(filter).cursor[JsObject]()
khanal sir
  • 103
  • 1
  • 9
  • What have you already tried? – cchantep Feb 08 '17 at 12:41
  • @cchantep I have updated my question – khanal sir Feb 09 '17 at 06:34
  • @cchantep I have updated my question again – khanal sir Feb 09 '17 at 12:32
  • 1
    The [JSON extended syntax](https://docs.mongodb.com/manual/reference/mongodb-extended-json/) doesn't define a way to pass some JavaScript expression in such query. Using the BSON serialization, the [`BSONJavaScript`](http://reactivemongo.org/releases/0.12/api/index.html#reactivemongo.bson.BSONJavaScript) could be tried. – cchantep Feb 09 '17 at 13:07

1 Answers1

2

In my case I was sure that I will get only 2 digits after decimal part so I did range query like

val lowerLimit = 4321.34
val upperLimit = lowerLimit + 0.01
val filter = Json.obj("$gte" -> JsNumber(lowerLimit),"$lt" -> JsNumber(upperLimit))) 
collection.find(filter).cursor[JsObject]()

The above query works only if we are sure that only two digit after decimal part is sent. If three digits after decimal part is sent we have to do val upperLimit = lowerLimit + 0.001.

khanal sir
  • 103
  • 1
  • 9