1

Consider an Invoice collection with the following documents:

{  "invoice_no" : "1001", "payable_amount" : 100, "paid_amount" : 50 }
{  "invoice_no" : "1002", "payable_amount" : 200, "paid_amount" : 200 }
{  "invoice_no" : "1003", "payable_amount" : 300, "paid_amount" : 150 }
{  "invoice_no" : "1004", "payable_amount" : 400, "paid_amount" : 400 }

Need those documents where payable_amount > paid_amount

Expected Result:

{  "invoice_no" : "1001", "payable_amount" : 100, "paid_amount" : 50 }
{  "invoice_no" : "1003", "payable_amount" : 300, "paid_amount" : 150 }
saif
  • 487
  • 1
  • 7
  • 19

1 Answers1

1

You'll find plenty of examples of using the $where operator for this but the aggregation framework can do this for you ...

db.collection.aggregate([
    {
        "$addFields": {
            "isPayableAmountGreater": { "$cmp": [ "$payable_amount", "$paid_amount" ] }
        }
    },
    { "$match": { "isPayableAmountGreater": 1 } }
])

Or, even simpler and without creating the (probably unwanted) isPayableAmountGreater quasi attribute:

db.collection.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$gt": [ "$payable_amount", "$paid_amount" ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])
glytching
  • 44,936
  • 9
  • 114
  • 120