繁体   English   中英

使用 C# 驱动程序查找 MongoDB 文档和仅匹配的数组元素

[英]Find MongoDB document and only matching array elements w/ C# driver

我正在尝试返回一个文档,并且该文档应该对其进行数组过滤,使其仅包含一项。 我见过很多类似的问题,但没有一个涉及动态查询。 可能有几个限制,所以我必须能够继续添加到过滤器中。

{
  "_id" : ObjectId("6058f722e9e41a3d243258dc"),
  "fooName" : "foo1",
  "fooCode" : 1,
  "bar" : [
    {
      "barCode" : "123",
      "barName" : "Rick's Cafe",
      "baz" : [
        {
          "bazId" : "00",
          "bazDescription" : "Ilsa"
        },
        {
          "bazId" : "21",
          "bazDescription" : "Victor"
        }
      ]
    },
    {
      "barCode" : "456",
      "barName" : "Draco Tavern",
      "baz" : [
        {
          "bazId" : "00",
          "bazDescription" : "Rick Shumann"
        }
      ]
    }
  ]
}

这是我的尝试,它返回一个包含条形码的数组的文档,并且包含数组的全部内容。

Expression<Func<Foo, bool>> filter = x => x.FooCode == 1;

string barCode = "456"
if (!String.IsNullOrEmpty(barCode))
{
  Expression<Func<Foo, bool>> newPred =
    x => x.Bar.Any(s => s.BarCode == barCode);
  filter = filter.CombineAnd(newPred);
}

var fooQuery =
  _fooCollection
    .Find(filter);

如何删除不匹配的数组元素,但前提是指定了数组元素?

您需要在 MongoDB 中使用聚合。 您可以使用unwind拆分数组元素,使用match过滤,select 使用projectgroup所需的键,例如 id 或其他内容。

MongoDB 聚合文档: https://docs.mongodb.com/manual/aggregation/

  1. Unwind以将单个文档转换为每个嵌套数组元素的文档,其形状为:
{
  "_id" : ObjectId("6058f722e9e41a3d243258dc"),
  "fooName" : "foo1",
  "fooCode" : 1,
  "bar": {
    "barCode" : "123",
    "barName" : "Rick's Cafe",
    ...
  }
}
  1. Match以找到您想要的元素
  2. Group以重新组合嵌套数组

因此生成的 C# 可能如下所示:

var fooQuery = _fooCollection.Aggregate()
                .Unwind("bar")
                .Match(BsonDocument.Parse("{ 'bar.barcode': '"+ barCode + "'}"))
                .Group(BsonDocument.Parse("{​​​​​ '_id':'$fooCode' }​​​​​"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM