[英]updating embedded array in MongoDB
I am trying to update the embedded array document in collection structure is 我正在尝试在集合结构中更新嵌入式数组文档
{
id: 1,
fields:[
{
"lang" : "eng","embeddedArray" : ["A","B","C"]
},
{
"lang" : "abcd","embeddedArray" :["A","D","E"]
}]
}
I want to update A with a in embeddedArray i try to update using this query but it is updating the entire array with 'a' instead of ['a','B','C'] 我想用一个EmbeddedArray更新A,我尝试使用此查询进行更新,但它使用'a'而不是['a','B','C']更新整个数组
db.collectionName.update({"fields.embeddedArray" : 'A'}, {"$set" : {"fields.$.embeddedArray" : "a"}});
Is their any way to update without loosing the other elements in array ? 他们有什么方法可以更新而不丢失数组中的其他元素吗?
Please check the below query : 请检查以下查询:
db.collectionName.find({"fields":{$elemMatch:
{"lang":"A"}}}).forEach(function(doc){
var fields = doc.fields;
var i,k;
for( i=0; i<fields.length; i++ )
{
k = fields[i].embeddedArray.indexOf("A");
fields[i].embeddedArray.splice(k,1,"a");
}
db.collectionName.update({ _id: doc._id},{$set:{"fields": fields}});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.