Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb find by comparing field values

Tags:

mongodb

Is it possible to express the following SQL query in mongodb:

SELECT * FROM table AS t WHERE t.field1 > t.filed2;

edit: To summarize:.

  1. using a third field storing "field1 - field2" is almost perfect, but requires a little extra maintenance.
  2. $where will load and eval in JavaScript and won't use any indexes. No good for large data.
  3. map/reduce has the same problem and will go trough all records even if we need only one
like image 497
Blago Avatar asked Jun 18 '11 23:06

Blago


People also ask

How do I compare two fields of the same collection in MongoDB?

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.

Can we use find and distinct together in MongoDB?

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.

How do I use $in in MongoDB?

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).


2 Answers

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.

like image 76
Andrew Orsich Avatar answered Nov 16 '22 04:11

Andrew Orsich


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.

like image 30
Karoly Horvath Avatar answered Nov 16 '22 02:11

Karoly Horvath