【问题标题】:Update list of list of list array mongo update更新列表数组列表的列表 mongo update
【发布时间】:2018-09-25 12:27:45
【问题描述】:
{
  "_id": "111de970-4f3f-4ae6-9d3b-396e60ff50aa",
  "ClaimNumber": 111,
  "Details": [
    {
      "Amount": "100",
      "Types": [
        {
          "InvoiceType": "OO",
          "Status": "N"
        },
        {
          "InvoiceType": "PP",
          "Status": "N"
        }
      ]
    },
    {
      "Amount": "100",
      "Types": [
        {
          "InvoiceType": "OO",
          "Status": "N"
        },
        {
          "InvoiceType": "SS",
          "Status": "N"
        }
      ]
    }
  ]
}
public class Type
{
    public string InvoiceType { get; set; }
    public string Status { get; set; }
}

public class Detail
{
    public string Amount { get; set; }
    public List<Type> Types { get; set; }
}

public class RootObject
{
    public string _id { get; set; }
    public int ClaimNumber { get; set; }
    public List<Detail> Details { get; set; }
}

我想在“_id”列和“Types.InvoiceType”时更新Details数组中Types数组“Status”=“P”的值= "OO" 值匹配。

请提供一个示例,说明如何在 c# 中使用 mongo 驱动程序实现。

【问题讨论】:

标签: c# arrays mongodb document


【解决方案1】:

你去吧:

var filter = Builders<RootObject>.Filter.Eq(o => o._id, "111de970-4f3f-4ae6-9d3b-396e60ff50aa");
var update = Builders<RootObject>.Update.Set($"{nameof(RootObject.Details)}.$[].{nameof(Detail.Types)}.$[elem].{nameof(Type.Status)}", "P");
var arrayFilter = new JsonArrayFilterDefinition<BsonDocument>($"{{ 'elem.{nameof(Type.InvoiceType)}': 'OO' }}");
var updateOptions = new UpdateOptions { ArrayFilters = new[] { arrayFilter } };
var result = new MongoClient()
    .GetDatabase("database")
    .GetCollection<RootObject>("collection")
    .UpdateOne(filter, update, updateOptions);

【讨论】:

  • 此代码会在一次更新中更新所有详细信息数组子值吗?是否有任何选项可以创建 linq 表达式以避免在过滤器定义中硬编码值?...
  • 是的,所有匹配的数组值都将在单个查询中更新。而且,是的,应该可以以更好的方式编写一些部分。如果您发布相关的 C# 类型,我可以尝试优化它。
  • 非常感谢您的快速响应,并且像魅力一样工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
  • 2020-01-07
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多