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

MongoDB报错:更新操作文档需含原子操作符,updateMany操作求助

解决MongoDB updateMany报错:"the update operation document must contain atomic operators"

你的问题出在两个地方:

  • 把upsert: true这个选项放进了更新操作的数组里,它应该作为updateMany的第三个独立参数传递
  • 虽然不是报错直接原因,但$substr是旧版操作符,MongoDB 4.0及以上版本更推荐用$substrBytes(按字节截取)或$substrCP(按Unicode字符截取),功能和$substr一致但命名更清晰

修正后的代码如下:

db.getCollection("Sales").updateMany(
  {"LocationId": {$regex : /^0/}},
  [{ 
    $set: { 
      LocationId: {  
        $substrBytes: ["$LocationId", 1, -1] 
      } 
    }
  }],
  { upsert: true }    
);

改动说明:

  • 将{ upsert: true }从更新操作数组中移出,作为updateMany的第三个参数单独传入
  • 替换$substr为$substrBytes,如果你的LocationId包含多字节字符(如中文),可换成$substrCP

执行修正后的代码即可正常批量更新符合条件的文档。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 12:40:35