C#mongodb-如何更新嵌套数组元素 [英] C# mongodb - how to update nested array elements
问题描述
我具有以下表示项目的JSON结构
I have the following JSON structure that represents an item
{
Id: "a",
Array1: [{
Id: "b",
Array2: [{
Id: "c",
Array3: [
{...}
]
}]
}]
}
我需要能够将Array2
中的数组元素替换为新项,或者仅将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.
这是我的代码来替换Array2
中的数组项:
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.$'"
这是我的代码,用于替换Array2
中的Array3
:
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)
);
这是错误:
"A write operation resulted in an error.
Too many positional (i.e. '$') elements found in path 'Array1.$.Array2.$.Array3'"
我正在使用C#MongoDB驱动程序2.5.0版和MongoDB 3.6.1版
I'm using C# MongoDB driver version 2.5.0 and MongoDB version 3.6.1
我发现这张Jira票证匹配嵌套数组的位置运算符表示问题是已修复,他们建议使用此语法进行更新
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"}
]}
)
并收到此错误:
cannot use the part (Array1 of Array.$[i].Array2.$[j].Array3) to traverse the element
关于如何解决此错误的任何想法?
Any ideas on how to solve this error?
推荐答案
这是您所需要的C#版本:
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);
这篇关于C#mongodb-如何更新嵌套数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!