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

MongoDB如何为数组中所有嵌入式文档添加字段

MongoDB 为数组所有嵌入式文档添加字段问题

我的集合中文档格式如下:

{posts: [{"name": "post1"},..., {"name": "postN"}]}

我原本使用以下语句,仅更新posts数组下标为0的嵌入式文档的lastMod字段为当前日期:

db.my_collection.update({}, { $set: {"posts.0.lastMod": new Date()}}, false, true)

现在想改为给数组中所有嵌入式文档添加lastMod字段,尝试执行:

db.my_collection.update({}, { $set: {"posts.lastMod": new Date()}}, false, true)

执行后报错,错误信息如下:

WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 28,
        "errmsg" : "Cannot create field 'lastMod' in element {posts: [ALL MY ARRAY WAS PRINTED HERE]"
}

解决方案

MongoDB 3.2 及以上版本(推荐)

使用$[]数组通配符操作符,它可以匹配数组中的所有元素,配合multi: true参数更新集合内的所有文档:

db.my_collection.update(
  {},
  { $set: { "posts.$[].lastMod": new Date() } },
  { multi: true }
)

MongoDB 3.2 以下版本

如果使用旧版本MongoDB,需要遍历集合中的每个文档,逐个更新数组内的元素:

db.my_collection.find().forEach(function(doc) {
  doc.posts.forEach(function(post) {
    post.lastMod = new Date();
  });
  db.my_collection.save(doc);
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:35:19