更新列表数组mongo更新列表

时间:2018-09-24 18:55:55

标签: c# arrays mongodb document

{
  "_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 ”值匹配。

请提供一个有关如何使用mongo驱动程序在c#中实现的示例。

1 个答案:

答案 0 :(得分: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);