How to use $ positional operator in MongoDB C# driver version 2

半腔热情 提交于 2019-11-28 00:53:35

问题


I need to update a field of one element from array sub document of a document.

MongoDB have the $ positional operator to do this. But in MongoDB C# driver version 2 it seems that there is no support for this operator.

How can I achieve this?

Documents:

{ "_id" : 1, "grades" : [ 80, 85, 90 ] }
{ "_id" : 2, "grades" : [ 88, 90, 92 ] }
{ "_id" : 3, "grades" : [ 85, 100, 90 ] }

Expected query:

db.students.update(
     { _id: 1, grades: 80 },
     { $set: { "grades.$" : 82 } }
   )

回答1:


You can try something like this.

var builder = Builders<Student>.Filter;
var filter = builder.Eq(student=> student.Id, 1) & builder.ElemMatch(student => student.Grades, x => x == 80);

var builder = Builders<Student>.Update;
var update = builder.Set(student => student.Grades[-1], 82);

var result = collection.UpdateOne(filter, update);


来源:https://stackoverflow.com/questions/42396877/how-to-use-positional-operator-in-mongodb-c-sharp-driver-version-2

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