使用MongoDB C#驱动程序2.2对嵌套字段进行强类型查询

new*_*bie 7 c# arrays mongodb mongodb-query mongodb-.net-driver

考虑以下结构

public class Parent
{
    public ObjectId Id { get; set; }    
    public IEnumerable<Child> Children { get; set; }
}

public class Child
{
    public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想找到所有父对象,其子值是数组的超集,即

var parents = new List<Parent>();
var values = new[] { "A", "B", "C" };
parents.Where(x => !values.Except(x.Children.Select(y => y.Value)).Any());
Run Code Online (Sandbox Code Playgroud)

要么

{ "Children.Value": { $all: ["A", "B", "C"] } }
Run Code Online (Sandbox Code Playgroud)

我想以键入的方式执行它,但谓词翻译器不支持Enumerable.Select所以这不起作用:

Builders<Parent>.Filter.All(x => x.Children.Select(y => y.Value), values);
Run Code Online (Sandbox Code Playgroud)

我目前正在使用此解决方法:

var filters = values.Select(x => Builders<Parent>.Filter.Where(y => y.Children.Any(z => z.Value == x)));
Builders<Parent>.Filter.And(filters);
Run Code Online (Sandbox Code Playgroud)

没有使用魔术字段名称字符串有更好的方法吗?

and*_*ian 0

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);
Run Code Online (Sandbox Code Playgroud)