如何使用 C# MongoDB.Driver 更新深度嵌套的数组?

我有这样的模型:


{  

   "_id":"5b90eea8c02e062be2888446",

   "storeGuid":"e97d4730-9b8a-49ed-be87-caf4054439aa",

   "storeId":"0",

   "storeDbName":"0",

   "tenant":"dev",

   "configGroup":[  

      {  

         "groupName":"peopleCounter",

         "config":[  

            {  

               "key":"averageWaitPeriodTime",

               "value":"60",

            }

         ]

      },

      {  

         "groupName":"sessionMonitor",

         "config":[  

            {  

               "key":"testKey1",

               "value":"987",

            },

            {  

               "key":"testKey2",

               "value":"123",

            }

         ]

      }

   ]

}

我正在尝试value更新"key":"testKey2"


我有这样的更新声明:


await coll.UpdateOneAsync(

    x => x.StoreGuid == storeGuid

         && x.ConfigGroup.Any(y => y.GroupName == groupName

                                   && y.Config.Any(z => z.Key == model.Key)),

    Builders<StoreModel>.Update.Set(x => x.ConfigGroup[-1].Config[-1].Value, model.Value));

例如,当我尝试groupName使用此类过滤器进行更新时,ConfigGroup[-1]它可以工作。

但是在我们拥有ConfigGroup[-1].Config[-1]它的情况下它不起作用。

我知道如何更新值的两个选项:

  • 只需使用更新整个列表 ConfigGroup[-1].Config

  • 或为过滤器指定具体索引,例如 ConfigGroup[configGroupIndex].Config[configKeyIndex].Value

但我想知道为什么它不适用于-1索引。以及如何正确地做到这一点。

请使用c# MongoDB.Driver回答。


临摹微笑
浏览 244回答 1
1回答

湖上湖

它不适用于乘法的原因是它与位置运算符'-1'相同。在“嵌套数组”主题下的官方文档中,我们可以看到以下内容:&nbsp;$位置 $ 运算符不能用于遍历多个数组的查询,例如遍历嵌套在其他数组中的数组的查询,因为 $ 占位符的替换是单个值从MongoDb 3.6 开始,有允许使用嵌套数组的新功能。全位置运算符过滤后的位置运算符:过滤位置运算符$[<identifier>]标识与更新操作的 arrayFilters 条件匹配的数组元素因此,使用过滤后的位置运算符,我的代码现在看起来像这样:await coll.UpdateOneAsync(x => x.StoreGuid == storeGuid,&nbsp; &nbsp; Builders<StoreModel>.Update.Set("configGroup.$[g].config.$[c].value", model.Value),&nbsp; &nbsp; new UpdateOptions&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; ArrayFilters = new List<ArrayFilterDefinition>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new BsonDocumentArrayFilterDefinition<BsonDocument>(new BsonDocument("g.groupName", groupName)),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new BsonDocumentArrayFilterDefinition<BsonDocument>(new BsonDocument("c.key", model.Key))&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP