MongoDB 用 C# 驱动程序替换数组内的数组

Ric*_*Bay 1 c# mongodb mongodb-query

我需要替换“baz”的内容。

{
  "_id" : ObjectId("6058f722e9e41a3d243258dc"),
  "fooName" : "foo1",
  "fooCode" : 1,
  "bar" : [
    {
      "barCode" : "123",
      "barName" : "Rick's Cafe",
      "baz" : [
        {
          "bazId" : "00",
          "bazDescription" : "Ilsa"
        },
        {
          "bazId" : "21",
          "bazDescription" : "Victor"
        }
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我从 UpdateOneAsync 和过滤器开始

Expression<Func<Foo, bool>> filter =
  f => f.fooCode == 1 &&
  f.Bar.Any(b => s.BarCode == "123")
Run Code Online (Sandbox Code Playgroud)

一旦我开始输入更新语句

Builders<Foo>.Update.Set(f => ??? , newBazArray);
Run Code Online (Sandbox Code Playgroud)

我意识到我可能做错了。我应该如何替换数组baz?

Joh*_*ica 8

你应该能够使用这个:

f => f.Bar[-1].baz
Run Code Online (Sandbox Code Playgroud)

where[-1]相当于 Mongo 查询中的位置运算符 ($)。

[-1]请注意,使用最新版本的 MongoDB 驱动程序(我认为是从 2.16.0 开始,但肯定是在 2.19.0 中),如果您使用位置运算符,您将得到以下异常:

MongoDB.Driver.Linq.ExpressionNotSupportedException:不支持表达式:mydocumentarray.get_Item(-1),因为负索引无效。要使用位置运算符 $,请使用 FirstMatchingElement 而不是索引值 -1。

因此f => f.Bar[-1].baz,您现在可以编写:

f => f.Bar.FirstMatchingElement().baz
Run Code Online (Sandbox Code Playgroud)

还有.FirstN(x)一个将更新前 x(例如 3)个匹配条目,以及.AllMatchingElements()将更新所有匹配项。

  • 从 2.19.0 驱动程序开始,使用 -1 表示位置运算符不再起作用(LINQ3 已成为默认的 LINQ 提供程序,并且 LINQ3 [不支持此语法](https://jira.mongodb.org/浏览/CSHARP-4079)) (2认同)