You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MongoDB中使用findOneAndUpdate对指定字段值执行加1操作

Mongoose findOneAndUpdate字段数值加1实现方案

直接使用MongoDB原生$inc原子操作符即可完成需求,该操作可以避免并发场景下的计数异常,同时兼容upsert自动创建文档的场景。

修改后的代码示例:

await mongo().then(async (mongoose) => {
  try {
    await userSchema.findOneAndUpdate(
      {
        _id: author.id
      },
      {
        $inc: {
          commandsUsed: 1
        }
      },
      {
        upsert: true,
        // 可选配置:new: true 会返回更新后的文档,无需求可删除
        new: true
      }
    )
  } finally {
    // 补充关闭连接逻辑,避免连接泄漏,按需添加
    mongoose.connection.close()
  }
})

相关说明:

  • $inc支持传入正负数实现数值的增减,比如传-1就是字段值减1
  • 操作本身为原子性,无需先查询字段值再修改回写,并发场景下不会出现计数偏差
  • 开启upsert: true时如果没有匹配到对应文档,会自动创建新文档,commandsUsed字段会被直接初始化为1,无需额外做字段初始化处理

内容的提问来源于stack exchange,提问作者Pinkhron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 22:54:02