使用 MongoDB C# 驱动程序 2.2 对嵌套字段进行强类型查询
本文关键字:强类型 查询 字段 MongoDB 驱动程序 使用 嵌套 | 更新日期: 2023-09-27 18:32:43
考虑以下结构
public class Parent
{
public ObjectId Id { get; set; }
public IEnumerable<Child> Children { get; set; }
}
public class Child
{
public string Value { get; set; }
}
我想找到所有父对象,其子值是数组的超集,即
var parents = new List<Parent>();
var values = new[] { "A", "B", "C" };
parents.Where(x => !values.Except(x.Children.Select(y => y.Value)).Any());
或
{ "Children.Value": { $all: ["A", "B", "C"] } }
我想以键入的方式执行此操作,但谓词转换器不支持枚举。选择此选项,因此这不起作用:
Builders<Parent>.Filter.All(x => x.Children.Select(y => y.Value), values);
我目前正在使用此解决方法:
var filters = values.Select(x => Builders<Parent>.Filter.Where(y => y.Children.Any(z => z.Value == x)));
Builders<Parent>.Filter.And(filters);
有没有更好的方法不使用魔术字段名称字符串?
IMongoClient _client = new MongoClient(@"mongodb://...");
IMongoDatabase _database = _client.GetDatabase("...");
IMongoCollection<Parent> _collection = _database.GetCollection<Parent>("q35135879");
var ca = new Child { Value = "A" };
var cb = new Child { Value = "B" };
var cc = new Child { Value = "C" };
var fdb = Builders<Parent>.Filter;
var filterLinq = fdb.All (x=>x.Children, new[] {ca, cb, cc});
var filterFieldDefinition = fdb.All("Children", new[] { ca, cb, cc });
var found1 = _collection.Find(filterLinq).ToList();
var found2 = _collection.Find(filterFieldDefinition ).ToList();
CollectionAssert.AreEqual(found1, found2);