过滤器生成器在 C# mongoDB 驱动程序中引发异常
Posted
技术标签:
【中文标题】过滤器生成器在 C# mongoDB 驱动程序中引发异常【英文标题】:Filter Builder throwing an exception in C# mongoDB Driver 【发布时间】:2021-11-03 20:15:06 【问题描述】:我正在尝试使用 c# mongo 驱动程序从 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(((documentFirstName == documentFirstName) AndAlso (documentLastName == documentLastName)))).'
【问题讨论】:
异常表示这种过滤器不受类型化方式的支持,但您仍然可以将其定义为简单的 BsonDocument(而不是使用 Builder)并将其传递给您的方法,而不是 FilterDefinition 【参考方案1】:答案迟到了。
建议:
生成nameFilters
。
对于FirstName
和 ($and
) LastName
,每个 nameFilter
必须相等 ($eq
)。
父过滤器 (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 查询
db.collection.find(
$expr:
$or: [
$and: [
$eq: [
"$FirstName",
"abc"
]
,
$eq: [
"$LastName",
"xyz"
]
]
,
// Other name filters
]
)
Sample Mongo Playground
【讨论】:
以上是关于过滤器生成器在 C# mongoDB 驱动程序中引发异常的主要内容,如果未能解决你的问题,请参考以下文章