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

假如有一个班级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}条";

4、删除Array中某个学生的方法

比如:删除生日为2010-10-1学生

UpdateDefinitionBuilder<BsonDocument> updateDefinitionBuilder = new UpdateDefinitionBuilder<BsonDocument>();
var updateDefinition = updateDefinitionBuilder.Pull(fieldDefinition, new BsonDocument { { "Birthday",Convert.ToDateTime("2010-10-1")} }); 
var result2 = MongoDBHelper.GetYeWuCollection<BsonDocument>("schoolclass").UpdateOne(filterUpdateDefinition, updateDefinition); 
string info2 = $"匹配到:{result2.ModifiedCount}条,更新:{result2.ModifiedCount}条"; 

其它类似操作仿照写即可

  

posted @ 2021-01-21 14:56  zhaogaojian  阅读(267)  评论(0编辑  收藏  举报