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"}}}])
– Quolonel Questions Feb 10 '16 at 10:30b
, it will use$b
as the right hand side of the comparison. This can be tested by executingdb.test.aggregate([{"$match":{"a":{"$eq":"$a"}}}])
. Zero results will be returned. – Paul Feb 7 '17 at 19:21db.test.find( {"$expr": {"$gt": ["$a", "$b"]}})
and in aggregation thrudb.test.aggregate( {"$match":{"$expr": {"$gt": ["$a", "$b"]}}})
– s7vr Dec 13 '17 at 21:48