在MongoDB中比较文档的2个字段 [英] Compare between 2 fields of a document in MongoDB

查看:111
本文介绍了在MongoDB中比较文档的2个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑包含以下文档的发票集合:

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 }

需要那些文件,其中payable_amount> paid_amount

Need those documents where payable_amount > paid_amount

预期结果:

{  "invoice_no" : "1001", "payable_amount" : 100, "paid_amount" : 50 }
{  "invoice_no" : "1003", "payable_amount" : 300, "paid_amount" : 150 }

推荐答案

您会发现许多使用

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 } }
])

或者,甚至更简单,并且没有创建(可能是不需要的)isPayableAmountGreater准属性:

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

db.collection.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$gt": [ "$payable_amount", "$paid_amount" ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

这篇关于在MongoDB中比较文档的2个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆