【问题标题】:How to calculate the amount with conditional?如何计算有条件的金额?
【发布时间】:2021-12-06 13:50:10
【问题描述】:

我在 MongoDB 中有这样的文档:

{
    "_id":{
        "$oid":"614e0f8fb2f4d8ea534b2ccb"
    },
    "userEmail":"abc@example.com",
    "customId":"abc1",
    "amountIn":10,
    "amountOut":0,
    "createdTimestamp":1632505743,
    "message":"",
    "status":"ERROR",
}

amountOut 字段可以是 0 或正数值。 我需要计算 amountInamountOut 字段的总和,前提是它是正数。
目前我正在这样做:

query = {
    'createdTimestamp': {'$gte': 1632430800},
    'createdTimestamp': {'$lte': 1632517200}
}
records = db.RecordModel.objects(__raw__=query).all()

total_amount = 0
for record in records:
    if record.amountOut > 0:
        total_amount += record.amountOut
    else:
        total_amount += record.amountIn

但这很慢。
我知道mongoengine 有一个sum 方法:

total_amount = db.PaymentModel.objects(__raw__=query).sum('amountIn')

但我不知道如何使用此方法的条件。
也许还有其他一些方法可以更快地计算出符合我需要的条件的金额?

【问题讨论】:

  • this 你在找什么吗?
  • @ray 是的,看起来这就是我需要的,但是我如何将它与mongoengine 一起使用?

标签: python-3.x mongodb mongoengine


【解决方案1】:

您可以使用 mongoengine 的 aggregation api,它只允许您正常执行聚合。

现在您可以在使用$cond 的代码中使用this 管道:

query = {
    'createdTimestamp': {'$gte': 1632430800, '$lte': 1632517200},
}
pipeline = [
    {"$match": query},
    {
        "$group": {
            "_id": None,
            "total_amount": {
                "$sum": {
                    "$cond": [
                        {
                            "$gt": [
                                "$amountOut",
                                0
                            ]
                        },
                        "$amountOut",
                        "$amountIn"
                    ]
                }
            }
        }
    }
]

records = db.RecordModel.objects().aggregate(pipeline)

Mongo Playground

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 2022-06-15
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多