【问题标题】:Using projected field in mongodb condition在 mongodb 条件下使用投影字段
【发布时间】:2021-10-01 20:32:16
【问题描述】:

我正在尝试使用 mongodb 聚合框架进行计算。所以我需要在另一种情况下使用投影项目(投影阶段的计算字段),但我无法得到结果。

这是我尝试的代码。

"$project": {
    "currency": {"$ifNull": ["$voucher_foreign_amount.symbol", "NOT ENTERED" ]},
    "amount": {"$cond": [{"$not": ["$voucher_foreign_amount"]}, "$voucher_amount", "$voucher_foreign_amount.amount"]},
    "voucher_type": 1,
    "voucher_payment_type": 1,
    "voucher_foreign_amount": 1,
    "station": 1,
    "paid": {"$cond": [{"$eq": ["$voucher_type",  "Paid"]}, "$amount", 1]}
   
}

在这个预测中,我无法获得付费字段,在我看来,这是因为最后一个条件不识别“$amount”。

那么,如何在另一个字段生成中使用金额字段?

【问题讨论】:

  • $amount只有在项目结束后才存在,解决方法可以是添加一个$set阶段只是在项目上方设置amount,或者保留1个项目并计算2次(第二个看起来更快)
  • @Takis_ 谢谢,两个项目解决了我的问题,如果你回答我会接受。

标签: mongodb


【解决方案1】:

我们添加的新字段$project/$set=$addFields 仅在阶段结束后存在。

我建议的两个解决方案是

  1. 添加一个$set阶段
{"$set" : {"amount" : {"$cond": [{"$not": ["$voucher_foreign_amount"]}, "$voucher_amount", "$voucher_foreign_amount.amount"]}}},
{"$project": {
    "currency": {"$ifNull": ["$voucher_foreign_amount.symbol", "NOT ENTERED" ]},
    "amount" : 1,
    "voucher_type": 1,
    "voucher_payment_type": 1,
    "voucher_foreign_amount": 1,
    "station": 1,
    "paid": {"$cond": [{"$eq": ["$voucher_type",  "Paid"]}, "$amount", 1]}
}}
  1. 计算 2 次​​li>
{
"$project": {
    "currency": {"$ifNull": ["$voucher_foreign_amount.symbol", "NOT ENTERED" ]},
    "amount": {"$cond": [{"$not": ["$voucher_foreign_amount"]}, "$voucher_amount", "$voucher_foreign_amount.amount"]},
    "voucher_type": 1,
    "voucher_payment_type": 1,
    "voucher_foreign_amount": 1,
    "station": 1,
    "paid": {"$cond": [{"$eq": ["$voucher_type",  "Paid"]},
                               {"$cond": [{"$not": ["$voucher_foreign_amount"]}, "$voucher_amount", "$voucher_foreign_amount.amount"]},
                               1]}
   }
}

您也可以像以前那样使用 2 个项目,但我认为 1 个 $set 仅带有 1 个字段更简单。

关于性能,我不知道MongoDB将如何执行它们(我过去测试过,我认为它优化了它(我测试了多个$map)),例如它可能是懒惰的,而不是计算$amount除非需要它的值,否则这 2 个阶段将在内部看起来为 1。 (在这种情况下,第一个会更快)

如果它不是懒惰的,那么第二个看起来会更快。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    相关资源
    最近更新 更多