使用 $set 和 $sum 在 mongodb 中更新数据

huangapple go评论49阅读模式
英文:

Updating data with $set and $sum mongodb

问题

我试图更新并汇总列的值。

await single_sku_db.collection("test").updateOne(
      { _id: ObjectId(id) },
      {
        $push: {
          report: {
            $each: [
              {
                name: name,
                views,
              },
            ],
            $position: 0,
          },
        },
        $set: {
          report_status: "Completed",
          total_views: { $sum: "$report.views" },
        },
      }

像这样不能像这样汇总report.views,会出现以下错误:

以美元符号($)为前缀的字段‘’对于存储无效。

是否有任何方法可以在不使用聚合的情况下执行此操作?

英文:

I was trying to do update and sum up the column value.

await single_sku_db.collection("test").updateOne(
      { _id: ObjectId(id) },
      {
        $push: {
          report: {
            $each: [
              {
                name: name,
                views,
              },
            ],
            $position: 0,
          },
        },
        $set: {
          report_status: "Completed",
          total_views: { $sum: "$report.views"},
        },
      }

I cant sum the report.views like this, will get this error.

> the dollar ($) prefixed field ‘’ is not valid for storage.

Is there anyway to do this without using aggregate?

答案1

得分: 2

一种选项是将$set替换为$inc,如下所示:

await single_sku_db.collection("test").updateOne(
  { _id: ObjectId(id) },
  {
    $push: {
      report: {
        $each: [
          {
            name: name,
            views,
          },
        ],
        $position: 0,
      },
    },
    $set: { report_status: "Completed" },
    $inc: { total_views: views },
  }
)

playground示例中查看其运行情况。

英文:

One option is to replace the $set with $inc for this:

await single_sku_db.collection("test").updateOne(
      { _id: ObjectId(id) },
      {
        $push: {
          report: {
            $each: [
              {
                name: name,
                views,
              },
            ],
            $position: 0,
          },
        },
        $set: {report_status: "Completed"},
        $inc: {total_views: views},
      })

See how it works on the playground example

huangapple
  • 本文由 发表于 2023年2月8日 18:15:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定