C#更新子文档
直接上代码
var filterBuilderUsers = Builders<RightUser>.Filter;
//根据userid找到要更新的rightUserList var rightUserList = MongoCollection.AsQueryable().Select(item=>item.RightUsers.Where(user=>user.UserId== userId)).Where(item=>item.Any()).ToList(); //foreach操作rightUserList,对每一个rightUser中的RightUser子文档下的RCID等于传入的RCId和userId等于userid的每一个符合查询条件结果的UserName更新为username
rightUserList.ForEach(rightUser=> { rightUser.ToList().ForEach(user => { var filter = Builders<DataRightModel>.Filter.ElemMatch("RightUsers", filterBuilderUsers.Eq("UserId", userId) & filterBuilderUsers.Eq("RCId", user.RCId)); var updateModel = Builders<DataRightModel>.Update.Set("RightUsers.$.UserName", userName); MongoCollection.UpdateMany(filter, updateModel); }); });
特别注意,查询的时候要用上$elemMatch,这样才能针对到确定的那一个,不然会出现更新到另外的地方
db.lktest.update( { "RightUsers":{$elemMatch:{"RCId":"3929224751377920","UserId": "643636024695552"}}}, { $set: { "RightUsers.$.UserName" : "ceshi" } } );
更新一般字段的时候
bool UpdateFieldOne(List<string> ptncIds, string appCode, string orgId, string sceneCode) {
//添加多个字段作为查询条件 var filter = Builders<PC_ProjectTemplate>.Filter.And( Builders<PC_ProjectTemplate>.Filter.Eq("AppCode", appCode), Builders<PC_ProjectTemplate>.Filter.Eq("OrganizationId", orgId), Builders<PC_ProjectTemplate>.Filter.Eq("SceneCode", sceneCode) );
//将字段UpdateFilterNodes字段的值更改为ptncids var updateModel = Builders<PC_ProjectTemplate>.Update.Set("UpdateFilterNodes", ptncIds); //var temp = GetMongoCollection().Find<PC_ProjectTemplate>(filter).FirstOrDefault(); var reData = GetMongoCollection().UpdateOne(filter, updateModel); return reData != null; }
备注:C#借助官方的Mongodb.Driver操作MongoDB时,更新操作,目前只能是对文档中的某一个字段进行更新,而不是对整个文档进行更新。