[英]Push field to each element of object array (MongoDB)
假設我有一些此類文件:
{
_id: ObjectId("5abe0f5add80a30001eff68d"),
obj_array: [
{
a: 1,
b: "some",
c: 134
},
{
a: 2,
b: "aaa",
c: 564
}
]
}
我需要做的是通過推送一個新字段 d: "new_value"
來更新所有obj_array
元素。 預期結果:
{
_id: ObjectId("5abe0f5add80a30001eff68d"),
obj_array: [
{
a: 1,
b: "some",
c: 134,
d: "new_value"
},
{
a: 2,
b: "aaa",
c: 564,
d: "new_value"
}
]
}
除了構建新的obj_array
對象並使用新數組設置doc.obj_array
,我沒有找到其他解決方案。 我想知道有沒有更優雅的方式做到這一點? 這是我的代碼:
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}})
})
您可以使用$[]
所有位置運算符來更新數組中的所有元素
myTable.update(
{ "_id": document._id },
{ "$set": { "obj_array.$[].d": "new_value" }}
)
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)
注意:如果使用nodeJS,則需要安裝異步,如果使用核心javascript,則可以更改為通用的for-each循環。
它總是對我有用:)
您可以通過遍歷$[]
並更新它來實現此目的:
對於單個更新:
db.getCollection('test').update({},{ "$set": { "array.$[].key": "Value" }})
多個更新:
db.getCollection('test').updateMany({},{ "$set": { "array.$[].key": "Value" }})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.