【问题标题】:Mongo conditionally sum values in project pipelineMongo有条件地对项目管道中的值求和
【发布时间】:2022-01-04 04:56:54
【问题描述】:

我正在尝试在值大于 100 的项目管道中添加,这些值是内部字段和对象,它们是数组的一部分。我有这样的事情:

数据库:

---客户集合---

client: {
    _id: 1,
    taxID: aldsfkjasdlñfk
    // other stuff
}

---发票收集---

invoice: {
    _id: 1,
    clientID: 1,
    total: 50
},
invoice: {
    _id: 2,
    clientID: 1,
    total: 150
},
invoice: {
    _id: 3,
    clientID: 1,
    total: 200
}

这是我的问题:

{
     $lookup: {
          from: 'invoices',
          localField: '_id',
          foreignField: 'client.id',
          as: 'invoices'
     }
},
{
     $project: {
          id: 1,
          taxID: aldsfkjasdlñfk,
          invoicesAmountGreaterThanOneHundred: {
               $sum: {
                   $cond: { if: { $gte: ['$invoices.total', 100] }, then: '$invoices.total', else: 0 }
               }
          }
     }
}

所以输出应该是:

{
     _id: 1.
     taxID: aldsfkjasdlñfk,
     invoicesAmountGreaterThanOneHundred: 350
}

我正在使用 Mongo 3.6.3。

未来我还会添加一个“invoicesAmountLesserThanOneHundred”,方法相同,但当然少于 100。

【问题讨论】:

  • 您可以使用$reduce 数组运算符得出$project 内的invoicesAmountGreaterThanOneHundred 值。

标签: javascript arrays mongodb aggregation-framework


【解决方案1】:

$sum之前使用$filter

db.client.aggregate([
  {
    $lookup: {
      from: "invoices",
      localField: "_id",
      foreignField: "clientID",
      as: "invoices"
    }
  },
  {
    $set: {
      "invoices": {
        "$filter": {
          "input": "$invoices",
          "as": "i",
          "cond": { $gte: [ "$$i.total", 100 ] }
        }
      }
    }
  },
  {
    $project: {
      id: 1,
      taxID: 1,
      invoicesAmountGreaterThanOneHundred: {
        $sum: "$invoices.total"
      }
    }
  }
])

mongoplayground


使用$reduce

db.client.aggregate([
  {
    $lookup: {
      from: "invoices",
      localField: "_id",
      foreignField: "clientID",
      as: "invoices"
    }
  },
  {
    $set: {
      "invoicesAmountGreaterThanOneHundred": {
        $reduce: {
          input: "$invoices",
          initialValue: "",
          in: {
            $sum: [
              "$$value",
              {
                $cond: {
                  if: { $gte: [ "$$this.total", 100 ] },
                  then: "$$this.total",
                  else: 0
                }
              }
            ]
          }
        }
      }
    }
  }
])

mongoplayground

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-26
  • 1970-01-01
  • 2021-06-05
  • 2021-03-25
  • 2020-11-01
相关资源
最近更新 更多