سؤال

I'm desperately looking for a solution of building an arithmetic MongoDB query with java. For example, how do I build the following query:

((test.value1 / test.value2) * 100) > 50 

I've tried the following query which didn't work:

{ {"$multiply" : [{"$divide" : ["$test.value1", "$test.value2"]}, "100"]} : {"$gt" : "50"}} 

I'm not sure if nested arithmetic operations like the one above are supported. Thanks in advance for any suggestion!!!

هل كانت مفيدة؟

المحلول

Lycha's answer is correct, $where is probably the only way to make such ad-hoc query. However it's quite slow and it can't use indexes.

If your expression always is in the same form (a / b > 50), I'd suggest precalculating result of that division in another field, indexing it and then querying this field directly.

If you need to perform many different queries with such expressions, then someone made a poor DB technology choice.

نصائح أخرى

You could try the $where operator that lets you give it the condition in Javascript:

Example:

{ $where: "this.value1/this.value2 > 50" }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top