Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何更新文档';s数组字段';使用Mongodb c#驱动程序的特定索引值?_C#_Mongodb_Mongodb Query - Fatal编程技术网

如何更新文档';s数组字段';使用Mongodb c#驱动程序的特定索引值?

如何更新文档';s数组字段';使用Mongodb c#驱动程序的特定索引值?,c#,mongodb,mongodb-query,C#,Mongodb,Mongodb Query,假设我有这样的数据 { _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 } ] } 如何在Mongodb C#驱动程序中更新文档数组字段(items)的第二项?我不想在mongojavascriptwrapper中这样做。我只想知道正确的语法。如何才能做到这一点?为了更新

假设我有这样的数据

{
 _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 }
   ]
}

如何在
Mongodb C#
驱动程序中更新文档数组字段
(items)
的第二项?我不想在
mongojavascript
wrapper中这样做。我只想知道正确的语法。如何才能做到这一点?

为了更新数组对象的元素,您必须首先检索数组对象(项),更新它,然后将其保存回去。下面应该让你做你需要的事情

// 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 }
);
//这不是一个格式正确的objectID,只是为了向您展示它的工作原理
var filter=Builders.filter.Eq(x=>x.\u id,ObjectId(“14577543”);
var data=collection.Find(filter.FirstOrDefault();
var element=data.items.ElementAt(1);//0索引。
元素y=2;
元素x=5;
collection.FindOneAndUpdate(
x=>x._id==ObjectId(“15477543”),
Builders.Update.Set(ri=>ri.items,data.items),
新建FindOneAndUpdateOptions(){IsUpsert=true}
);
看一看。这可能会有帮助。