数据库
首页 > 数据库> > MongoDb C# 操作键值为Array对象的方法

MongoDb C# 操作键值为Array对象的方法

作者:互联网

假如有一个班级Collection(Grade,Array Student),班级下有学生Student(Birthday,Sex,Name)

1、先定义一个fieldDefinition和updateDefinition

FieldDefinition<BsonDocument> fieldDefinition = "StudentList";
FilterDefinitionBuilder<BsonDocument> filterDefinitionZiBuilder = new FilterDefinitionBuilder<BsonDocument>();
FilterDefinition<BsonDocument> filterZi = filterDefinitionZiBuilder.And(
   filterDefinitionZiBuilder.Eq("Birthday", Convert.ToDateTime("2010-10-1")),
   filterDefinitionZiBuilder.Eq("Sex", "male")
);
FilterDefinition<BsonDocument> filterDefinition = filterDefinitionBuilder.And(
   filterDefinitionBuilder.Eq("Grade", 3),
   filterDefinitionBuilder.ElemMatch(fieldDefinition, filterZi));

2、插入一个学生方法如下(这里构建的filterDefinition不需要ElemMatch那句话)

UpdateDefinitionBuilder<BsonDocument> updateDefinitionBuilder = new UpdateDefinitionBuilder<BsonDocument>();
var updateDefinition = updateDefinitionBuilder.AddToSet(fieldDefinition, item);
var result2 =database.GetCollection<SchoolClass>("schoolclass").UpdateOne(filterDefinition, updateDefinition);
string info2 = $"匹配到:{result2.ModifiedCount}条,更新:{result2.ModifiedCount}条";

3、更新学生生日方法

UpdateDefinitionBuilder<BsonDocument> updateDefinitionBuilder = new UpdateDefinitionBuilder<BsonDocument>();
var updateDefinition = updateDefinitionBuilder.Set("StudentList.$.Birthday", dateBirthday);
var result2 =database.GetCollection<SchoolClass>("schoolclass").UpdateOne(filterUpdateDefinition, updateDefinition);
string info2 = $"匹配到:{result2.ModifiedCount}条,更新:{result2.ModifiedCount}条";

其它类似操作仿照写即可

  

标签:UpdateDefinitionBuilder,C#,MongoDb,result2,ModifiedCount,var,键值,fieldDefinition,
来源: https://www.cnblogs.com/zhaogaojian/p/14308044.html