mongodb find by comparing field values

前端 未结 3 655

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

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

edit:

相关标签:
3条回答
  • 2020-12-14 12:48

    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.

    0 讨论(0)
  • 2020-12-14 12:59

    You can use a $where. Just be aware it will be fairly slow (has to execute Javascript code on every record) so combine with indexed queries if you can.

    db.T.find( { $where: function() { return this.Grade1 > this.Grade2 } } );
    

    or more compact:

    db.T.find( { $where : "this.Grade1 > this.Grade2" } );
    
    0 讨论(0)
  • 2020-12-14 13:03

    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.

    0 讨论(0)
提交回复
热议问题