1

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!!!

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

First of all, thank you. Do you think it would be better if I query only the values, in this example value1 and value2, and do the calculation on application side?
This way you'd have to load all records to the application, only to discard some of them next moment. If there are few of them (e.g. < 100), this might not be a problem.
Unfortunately, there are more than 1000 records. Then the $where query is the better choice, isn't it? What about the aggregation framework? There are no examples in the documentation, therefore I have no idea of how the query has to look like.
Aggregation framework is not released yet. And it also won't let you use expressions. If you need high performance - precalculate and index. If you need flexibility - use $where.
Sorry one last question: I was wondering If I could do this with MapReduce and for example return the ids of all matching documents. Is that possible?
|
1

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

Example:

{ $where: "this.value1/this.value2 > 50" }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.