本文介绍了如何使用 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",
            }
         ]
      }
   ]
}

我正在尝试更新 "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));

当我尝试使用这样的过滤器 ConfigGroup[-1] 更新例如 groupName 时,它会起作用.

When i try to update for example groupName using such filter ConfigGroup[-1] it works.

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

But in the case when we have ConfigGroup[-1].Config[-1] it does not work.

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

I know two options how to update the value:

  • 只需使用 ConfigGroup[-1].Config
  • 更新整个列表
  • 或为过滤器指定具体的索引,例如 ConfigGroup[configGroupIndex].Config[configKeyIndex].Value

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

But i want to know why it does not work with -1 index.And how to do it properly.

请使用 c# MongoDB.Driver 回答.

提前致谢.

推荐答案

用multiply '-1'不行的原因是因为和位置运算符 $.在嵌套数组"主题下的官方文档中,我们可以看到下一个:

The reason why it does not work with multiply '-1' because it is the same as positional operator $.In official documentation under the subject of "Nested Arrays" we can see next:

位置$运算符不能用于遍历的查询多个数组,例如遍历嵌套数组的查询在其他数组中,因为 $ 占位符的替换是单个值

MongoDb 3.6 开始,有一些新功能可以处理嵌套数组.

From MongoDb 3.6 there are new features that allow to work with nested arrays.

全位置运算符

过滤后的位置运算符:

过滤后的位置运算符 $[] 标识数组与 arrayFilters 条件匹配以进行更新的元素操作

所以,使用过滤位置运算符,我的代码现在看起来像这样:

So, using the filtered position operator my code looks like this now:

await coll.UpdateOneAsync(x => x.StoreGuid == storeGuid,
    Builders<StoreModel>.Update.Set("configGroup.$[g].config.$[c].value", model.Value),
    new UpdateOptions
    {
        ArrayFilters = new List<ArrayFilterDefinition>
        {
            new BsonDocumentArrayFilterDefinition<BsonDocument>(new BsonDocument("g.groupName", groupName)),
            new BsonDocumentArrayFilterDefinition<BsonDocument>(new BsonDocument("c.key", model.Key))
        }
    });

这篇关于如何使用 C# MongoDB.Driver 更新深度嵌套的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 22:00