C# mongodb - how to update nested array elements

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

I have the following JSON structure that represents an item

{     Id: "a",     Array1: [{         Id: "b",         Array2: [{             Id: "c",             Array3: [                 {...}             ]         }]     }] } 

I need to be able to either replace the array element in Array2 with a new item or to replace just Array3 with a new array.

Here is my code to replace the array item in Array2:

await Collection.UpdateOneAsync(     item => item.Id.Equals("a") &&     item.Array1.Any(a => a.Id.Equals("b")) &&     item.Array1[-1].Array2.Any(b => b.Id.Equals("c")),     Builders<Item>.Update.Set(s => s.Array1[-1].Array2[-1], newArray2Item) ); 

When executing this code I'm getting this error:

"A write operation resulted in an error.  Too many positional (i.e. '$') elements found in path 'Array1.$.Array2.$'" 

Here is my code to replace Array3 within Array2:

await Collection.UpdateOneAsync(         item => item.Id.Equals("a") &&         item.Array1.Any(a => a.Id.Equals("b")) &&         item.Array1[-1].Array2.Any(b => b.Id.Equals("c")),         Builders<Item>.Update.Set(s => s.Array1[-1].Array2[-1].Array3, newArray3)     ); 

And this is the error:

"A write operation resulted in an error.  Too many positional (i.e. '$') elements found in path 'Array1.$.Array2.$.Array3'" 

I'm using C# MongoDB driver version 2.5.0 and MongoDB version 3.6.1

I found this Jira ticket Positional Operator Matching Nested Arrays that says the problem was fixed and they suggested this syntax for the update

Update all matching documents in nested array:  db.coll.update({}, {$set: {“a.$[i].c.$[j].d”: 2}}, {arrayFilters: [{“i.b”: 0}, {“j.d”: 0}]}) Input: {a: [{b: 0, c: [{d: 0}, {d: 1}]}, {b: 1, c: [{d: 0}, {d: 1}]}]} Output: {a: [{b: 0, c: [{d: 2}, {d: 1}]}, {b: 1, c: [{d: 0}, {d: 1}]}]} 

So I converted it to my elements:

db.getCollection('Items').update( {"Id": "a"}, {$set: {"Array1.$[i].Array2.$[j].Array3": [newArray3]}},  {arrayFilters:      [         {"i.Id": "b"},          {"j.Id": "c"}     ]} ) 

And got this error:

cannot use the part (Array1 of Array.$[i].Array2.$[j].Array3) to traverse the element 

Any ideas on how to solve this error?

回答1:

Here's the C# version of what you need:

var filter = Builders<Item>.Filter.Eq("Id", "a"); var update = Builders<Item>.Update.Set("Array1.$[i].Array2.$[j].Array3", new[] { new Item { Id = "d" } }); var arrayFilters = new List<ArrayFilterDefinition> { new JsonArrayFilterDefinition<Item>("{'i.Id': 'b'}"), new JsonArrayFilterDefinition<Item>("{'j.Id': 'c'}") }; var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters }; collection.UpdateOne(filter, update, updateOptions); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!