Use the $expr operator.
Introduced in version 3.6, $expr can build query expressions that compare fields from the same document.
Compare Two Fields from A Single Document (example taken directly from MongoDB Docs):
Consider an monthlyBudget collection with the following documents:
{ "_id" : 1, "category" : "food", "budget": 400, "spent": 450 }
{ "_id" : 2, "category" : "drinks", "budget": 100, "spent": 150 }
{ "_id" : 3, "category" : "clothes", "budget": 100, "spent": 50 }
{ "_id" : 4, "category" : "misc", "budget": 500, "spent": 300 }
{ "_id" : 5, "category" : "travel", "budget": 200, "spent": 650 }
The following operation uses $expr to find documents where the spent amount exceeds the budget:
db.monthlyBudget.find( { $expr: { $gt: [ "$spent" , "$budget" ] } } )
The operation returns the following results:
{ "_id" : 1, "category" : "food", "budget" : 400, "spent" : 450 }
{ "_id" : 2, "category" : "drinks", "budget" : 100, "spent" : 150 }
{ "_id" : 5, "category" : "travel", "budget" : 200, "spent" : 650 }
a, not$a, i.e.db.test.aggregate([{"$match":{"a":{"$gt":"$b"}}}])b, it will use$bas the right hand side of the comparison. This can be tested by executingdb.test.aggregate([{"$match":{"a":{"$eq":"$a"}}}]). Zero results will be returned.db.test.find( {"$expr": {"$gt": ["$a", "$b"]}})and in aggregation thrudb.test.aggregate( {"$match":{"$expr": {"$gt": ["$a", "$b"]}}})