MongoDB更新嵌套数组对象,其中数组文档中存在匹配项

时间:2016-10-11 15:47:18

标签: c# mongodb

这是我的MongoDB文档

{  
   "_id":20,
   "GroupId":"45",
   "Name":"Some Name",
   "NestedArray":[  
      {  
         "Id":3,
         "Name":"NesName",
         "IsDeleted":false
      }
   ]
}

我需要编写一个更新语句,如(在SQL解释中)

update MyCollections.NestedArray set MyCollections.NestedArray[x].IsDeleted = true where MyCollections.NestedArray[x].Id = 3

这是我试过的

 var groupFilter = Builders<MyType>.Filter.Eq(x => x.Id, 45);
 var nestedArayDocUpdate = Builders<MyType>.Update.Set(x => x.NestedArray[0].IsDeleted, true);
 mongoDbRepository.UpdateMany(groupFilter, nestedArayDocUpdate,
               new UpdateOptions {IsUpsert = false, BypassDocumentValidation = false});

使用MongoDB 3.2如何才能提出MongoDB C#驱动程序查询?

1 个答案:

答案 0 :(得分:0)

这就是我最终做到的方式。

 var updateBuilder = Builders<Type>.Update.
                           .Set(x => x.NestedArray[-1].IsActive, false)
                           .Set(x => x.NestedArray[-1].IsDeleted, true);

mongoDbRepository.UpdateOne( Builders<Type>.Filter.Where( 
   x => x.NestedArray.Any(c => c.Id == categoryId)), updateBuilder);