假设我有这样的数据
{
_id: '14577543',
items: [
{ x: 0, y: 0, z: 0 }
{ x: 0, y: 0, z: 0 }
{ x: 0, y: 0, z: 0 }
{ x: 0, y: 0, z: 0 }
]
}
我该如何更新(items)
驱动程序中文档数组字段Mongodb C#
的第二项?我不希望在Mongo Javascript
包装器中执行此操作。我只想知道正确的语法。我该怎么办?
答案 0 :(得分:0)
为了更新数组对象的元素,您必须首先检索该数组对象(项目),对其进行更新,然后将其保存回去。以下应该可以帮助您完成所需的工作。
// This is not a correct formatted objectID but to show you how it 'would' work
var filter = Builders<ClassObject>.Filter.Eq(x => x._id, ObjectId("14577543"));
var data = collection.Find(filter).FirstOrDefault();
var element = data.items.ElementAt(1); // 0 indexed.
element.y = 2;
element.x = 5;
collection.FindOneAndUpdate<ClassObject>(
x => x._id == ObjectId("15477543"),
Builders<ClassObject>.Update.Set(ri => ri.items, data.items),
new FindOneAndUpdateOptions<ClassObject, ClassObject>() { IsUpsert = true }
);