MongoDb query condition on comparing 2 fields

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" } );

UPD for mongodb v.3.6+

you can use $expr as described in recent answer

Leave a Comment