我正在尝试对 mongodb 版本 4.4.12 的 $updateOne 中的两个字段进行加法和减法 - 如何使用 $add 和 $subtract $set 这些字段?

发布于 2025-01-12 15:58:36 字数 602 浏览 0 评论 0原文

db.collection.updateOne({
    someId: "myId",
},
{
    $set: {
        startDate: {
            $subtract: ["$startDate", 18000000] // this is 5 hours in ms
        },
        endDate: {
            $add: ["$endDate", 18000000]
        }
    }
})

上面是我当前的代码,有一些名称更改。我想知道如何通过减法和加法更新文档的 startDate 和 endDate 字段,但是当我运行此命令时,我没有得到任何更改。

我已经检查了文档,我无法使用 $dateAdd 因为我使用的是 4.4.12 并且需要 5.0;同样在 updateOne 文档中,我没有看到任何加法或减法的示例。

我也收到了错误: 尝试以这种方式执行此操作时,“endDate.$add”中的美元 ($) 前缀字段“$add”对于存储无效。。我尝试使用 $update 即使它已被弃用,但这显然不起作用。

有人看到任何明显的问题,或者有如何解决这个问题的建议吗?

db.collection.updateOne({
    someId: "myId",
},
{
    $set: {
        startDate: {
            $subtract: ["$startDate", 18000000] // this is 5 hours in ms
        },
        endDate: {
            $add: ["$endDate", 18000000]
        }
    }
})

Above is the current code I have, with a few name changes. I want to know how I can update the doc's startDate and endDate fields with subtraction and addition, but when I run this I don't get any changes.

I have checked the documentation, and I can't use $dateAdd because I'm on 4.4.12 and that requires 5.0; also in the updateOne documentation I don't see any examples with addition or subtraction.

I've also gotten the error:
The dollar ($) prefixed field '$add' in 'endDate.$add' is not valid for storage. when trying to do it this way. I tried using $update even though that's deprecated, but that obviously didn't work.

Does anyone see any glaring issues, or have a recommendation of how to solve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

聊慰 2025-01-19 15:58:36

查询

  • 当我们使用聚合运算符进行更新时,我们必须使用管道更新
  • 来使其成为管道更新,这里我们只需要用 [] 括起来,就像
    [{$set ..........}]
  • 我们不能将聚合运算符与更新运算符混合使用,我们使用其中之一或另一个,当我们使用管道更新时,我们将阶段放入 []
  • 管道更新需要 MongoDB >= 4.2
db.collection.update({
    someId: "myId",
},
[{
    $set: {
        startDate: {
            $subtract: ["$startDate", 18000000] // this is 5 hours in ms
        },
        endDate: {
            $add: ["$endDate", 18000000]
        }
    }
}],
{"multi" : false})

Query

  • when we use aggregate operators for the update, we have to use a pipeline update
  • to make it a pipeline update here we only need to surround with [] like
    [{$set ..........}]
  • we can't mix aggregate operators with update operators, we use either the one or the other, and when we use pipeline update we put the stages into []
  • pipeline updates need MongoDB >= 4.2
db.collection.update({
    someId: "myId",
},
[{
    $set: {
        startDate: {
            $subtract: ["$startDate", 18000000] // this is 5 hours in ms
        },
        endDate: {
            $add: ["$endDate", 18000000]
        }
    }
}],
{"multi" : false})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文