MongoDB .Net 驱动程序 - 过滤器生成器抛出异常

MongoDB .Net Driver - Filter Builder throwing an exception

我正在尝试使用 C# MongoDB 驱动程序从 MongoDB 获取文档。

public class Record
{
    [BsonId]
    public ObjectId Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Data { get; set; }
}

public class Name
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

var Names = new List<Names>;
Names.Add(new Name(FirstName = "abc", LastName = "xyz"));
Names.Add(new Name(FirstName = "123", LastName = "789"));
Names.Add(new Name(FirstName = "a1b2", LastName = "c7d8"));

我尝试了以下查询来过滤和获取所需的文档。但是此查询失败并抛出异常。

FilterDefinition<Record> patentFilter = Builders<Record>.Filter.Where(y => Names.Any(x=> x.Name == y.Name && x.LastName == y.LastName));

异常:

System.ArgumentException: 'Unsupported filter: Any(value(Name]).Where((({document}{FirstName} == {document}{FirstName}) AndAlso ({document}{LastName} == {document}{LastName})))).'

回答晚了。

会建议:

  1. 生成nameFilters

    对于 FirstName 和 ($and) LastName.

    ,每个 nameFilter 必须满足相等的 ($eq)
  2. 父过滤器 (filter) 将 nameFilters$or 链接起来。

    任何满足 nameFilter 的文件都将被退回。

var names = new List<Name>();
names.Add(new Name { FirstName = "abc", LastName = "xyz" });
names.Add(new Name { FirstName = "123", LastName = "789" });
names.Add(new Name { FirstName = "a1b2", LastName = "c7d8" });

List<FilterDefinition<Record>> namefilters = new List<FilterDefinition<Record>>();

foreach (var name in names)
{
    FilterDefinition<Record> namefilter = Builders<Record>.Filter.And(
        Builders<Record>.Filter.Eq(x => x.FirstName, name.FirstName),
        Builders<Record>.Filter.Eq(x => x.LastName, name.LastName)
    );

    namefilters.Add(namefilter);
}

FilterDefinition<Record> filter = Builders<Record>.Filter.Or(namefilters);

var filteredRecords = _collection.Find(filter)
    .ToList();

MongoDB query

db.collection.find({
  $expr: {
    $or: [
      {
        $and: [
          {
            $eq: [
              "$FirstName",
              "abc"
            ]
          },
          {
            $eq: [
              "$LastName",
              "xyz"
            ]
          }
        ]
      },
      // Other name filters
    ]
  }
})

Sample Mongo Playground