使用 C# 针对 Mongodb 的数组字段创建 In 过滤器

Create an In filter against an array field of Mongodb using c#

我在 C# 中有一个类似于下面的对象。我想找到匹配的人对象,其中包含与提供的 type 匹配的项目,并且该项目的 sourceId 也存在于提供的数组中 sourceIds:

Person: {
  id: 1,
  items: [
    {
      type: "one",
      sourceId: 2
    },
    {
      type: "two"
      sourceId: 3
    }
  ]
}

到目前为止我已经想出了这个:

var filter = Builders<Person>.Filter.In(p => p.items.Where(i => i.type == "one").FirstOrDefault().sourceId, providedIds);
var results = PersonCollection.FindAsync(filter);

当我 运行 时,我得到这个错误:

Unable to determine the serialization information for p => p.items.Where(i => (i.type == "one")).FirstOrDefault().sourceId

据我所知,Mongo 驱动程序似乎不理解 FirstOrDefault(或者也可能是 Where)。我该如何完成这个查询?

MongoDB .NET 驱动程序无法解释您的过滤器并将其翻译成 MongoDB 查询语言。

您必须改用 $elemMatch,过滤器可能如下所示:

{ "items" : { "$elemMatch" : { "type" : "one", "sourceId" : { "$in" : [1, 2, 3] } } } }

C# 版本:

var filter = Builders<Person>.Filter.ElemMatch(f => f.items,
            item => item.type == "one" && providedIds.Contains(item.sourceId));

它生成与我在上面粘贴的 $elemMatch 完全相同的语句