首页 > 解决方案 > 使用 C# 驱动程序查找 MongoDB 文档并仅匹配数组元素

问题描述

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

{
  "_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);

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

标签: c#mongodbmongodb-query

解决方案


您需要在 MongoDB 中使用聚合。您可以使用unwind拆分数组元素,使用match过滤,使用project选择您想要的键,并使用 id 之类的公共列进行分组。

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


推荐阅读