[英]Push field to each element of object array (MongoDB)
Let's say I have some documents of such type: 假设我有一些此类文件:
{
_id: ObjectId("5abe0f5add80a30001eff68d"),
obj_array: [
{
a: 1,
b: "some",
c: 134
},
{
a: 2,
b: "aaa",
c: 564
}
]
}
What I need to do is to update all the obj_array
elements by pushing a new field d: "new_value"
. 我需要做的是通过推送一个新字段
d: "new_value"
来更新所有obj_array
元素。 Expected result: 预期结果:
{
_id: ObjectId("5abe0f5add80a30001eff68d"),
obj_array: [
{
a: 1,
b: "some",
c: 134,
d: "new_value"
},
{
a: 2,
b: "aaa",
c: 564,
d: "new_value"
}
]
}
I didn't find any other solution but constructing new obj_array
object and setting doc.obj_array
with the new array. 除了构建新的
obj_array
对象并使用新数组设置doc.obj_array
,我没有找到其他解决方案。 I wonder is there some more elegant way to do that? 我想知道有没有更优雅的方式做到这一点? Here's my code:
这是我的代码:
myTable.find().forEach(function(document) {
var new_array = [];
document.obj_array.forEach(function(elem) {
elem.d = "new_value";
new_array.push(elem);
})
myTable.update({_id: document._id}, {$set: {obj_array: new_array}})
})
1: run command npm install async --save
1:运行命令npm install async --save
db.collection.find({_id:ObjectId("5abe0f5add80a30001eff68d")},function(err, result){
if(result){
async.eachSeries(result.obj_array,function(value, cb){
value.d = "new_value";
return cb();
},function(){
console.log(result)
})
}
})
//Once you get perfect result you can execute update query
db.collection.update({_id:ObjectId("5abe0f5add80a30001eff68d")},result)
NOTE: If you work with nodeJS then you need to install async, if you work with core javascript then you can change to common for-each loop.
注意:如果使用nodeJS,则需要安装异步,如果使用核心javascript,则可以更改为通用的for-each循环。
its always work for me :)
它总是对我有用:)
You can simply achieve this by traverse array through $[]
and update it: 您可以通过遍历
$[]
并更新它来实现此目的:
for single update: 对于单个更新:
db.getCollection('test').update({},{ "$set": { "array.$[].key": "Value" }})
multiple updates: 多个更新:
db.getCollection('test').updateMany({},{ "$set": { "array.$[].key": "Value" }})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.