【问题标题】:How to use the sum of two fields when searching for a document in MongoDB?在 MongoDB 中搜索文档时如何使用两个字段的总和?
【发布时间】:2021-06-21 15:07:03
【问题描述】:

我有一个帐户集合,我正在尝试查找其中targetAmount >= totalAmount + N 的帐户

{
  "_id": {
    "$oid": "60d097b761484f6ad65b5305"
  },
  "targetAmount": 100,
  "totalAmount": 0,
  "highPriority": false,
  "lastTimeUsed": 1624283088
}

现在我只需选择所有帐户,遍历它们并检查是否满足条件。但我试图在查询中完成这一切:

amount = 10

tasks = ProviderAccountTaskModel.objects(
    __raw__={
        'targetAmount': {
            '$gte': {'$add': ['totalAmount', amount]}
        }
    }
).order_by('-highPriority', 'lastTimeUsed')

我也尝试过使用$sum,但是这两个选项都不起作用。
搜索时不能用,还是我走错路了?

【问题讨论】:

    标签: python mongodb mongoengine


    【解决方案1】:

    您可以使用$where。请注意,它会相当慢(必须在每条记录上执行 Javascript 代码),所以如果可以的话,请结合索引查询。

    db.getCollection('YourCollectionName').find( { $where: function() { return this.targetAmount > (this.totalAmount + 10) } })
    

    或者更简洁的方式是

    db.getCollection('YourCollectionName').find( { $where: "this.targetAmount > this.totalAmount +  10" })
    

    【讨论】:

    • 哇,直到现在才知道这是可能的。很好的答案。在哪里可以通过示例了解更多信息?
    • $where 可能是这个文档可以帮助你。@hhharsha36
    【解决方案2】:

    您必须使用聚合而不是 find 命令,因为除了算术运算之外,文档的自引用将不起作用。

    以下是您要查找的聚合命令。将其转换为 motoengine 等效命令。

    db.collection.aggregate([
      {
        "$match": {
          "$expr": {
            "$gte": [
              "$targetAmount",
              {
                "$sum": [
                  "$totalAmount",
                  10
                ]
              },
            ],
          },
        },
      },
      {
        "$sort": {
          "highPriority": -1,
          "lastTimeUsed": 1,
        },
      },
    ])
    

    Mongo Playground Sample Execution

    【讨论】:

      猜你喜欢
      • 2016-02-28
      • 1970-01-01
      • 2021-05-16
      • 2022-11-28
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 2023-04-08
      • 2020-04-13
      相关资源
      最近更新 更多