You cannot do this directly with a MongoDB query. Queries in MongoDB allow only static values ββto be compared. However, there are several options.
First of all, you can just save the comparison result whenever you update the values ββin each field, i.e. You can save it as:
home away gt 1 3 0 2 1 1 1 0 1 4 5 0
This is the simplest solution and has the added benefit you can set for an index on gt . Of course, when updating the values, this means additional overhead. Performing this kind of preliminary calculation is very similar to denormalization. Denormalization is something you often have to do in NoSQL databases to make the most of the system.
There is an alternative, but that will not allow you to perform an indexed search on > . You can use the aggregation structure as follows:
db.so.aggregate( [ { $project: { 'away' : 1, 'home': 1, 'better_at_home': { $cmp: [ '$home', '$away' ] } } }, { $match: { 'better_at_home': { $gt: 0 } } } ] );
In the first step, we use $cmp to compare home and away . In the second stage ( $match ), we then filter out all documents where the difference is less than or equal to 0.
Aggregation Response:
{ "result" : [ { "_id" : ObjectId("51ee7cfb812db9ff4412f12f"), "home" : 2, "away" : 1, "better_at_home" : 1 }, { "_id" : ObjectId("51ee7cff812db9ff4412f130"), "home" : 1, "away" : 0, "better_at_home" : 1 } ], "ok" : 1 }