本文介绍了如何在MongoDB C#驱动程序版本2中使用$位置运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要更新文档的数组子文档中一个元素的字段.
I need to update a field of one element from array sub document of a document.
MongoDB具有$位置运算符来执行此操作.但是在MongoDB C#驱动程序版本2中,似乎不支持此运算符.
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.
我该如何实现?
文档:
{ "_id" : 1, "grades" : [ 80, 85, 90 ] }
{ "_id" : 2, "grades" : [ 88, 90, 92 ] }
{ "_id" : 3, "grades" : [ 85, 100, 90 ] }
预期查询:
db.students.update(
{ _id: 1, grades: 80 },
{ $set: { "grades.$" : 82 } }
)
推荐答案
您可以尝试类似的方法.
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);
这篇关于如何在MongoDB C#驱动程序版本2中使用$位置运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!