Is it possible to express the following SQL query in mongodb:
SELECT * FROM table AS t WHERE t.field1 > t.filed2;
edit: To summarize:.
MongoDB compare two fields in the same document You can use the $where operator to compare the fields. When we have a given condition where we have to compare multiple properties on the same field.
Both the find and distinct operations are very useful when it comes to retrieving data from MongoDB. The find operation returns the data all at once or according to the query and projection. The distinct operation has a special functionality of retrieving unique values of a specified field.
For comparison of different BSON type values, see the specified BSON comparison order. If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array (for example, <value1> , <value2> , and so on).
You can do this using $where:
db.coll.find( { $where: "this.field1 > this.field2" } );
But:
Javascript executes more slowly than the native operators, but it is very flexible
If performance is an issue better to go with way suggested by @yi_H.
You could store in your document field1 - field2
as field3
, then search for { field3: { $gt: 0 } }
It also possible to get matching documents with mapreduce.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With