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
相关产品推荐
相关产品推荐

