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

时间:2016-02-01 16:50:31

标签: 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; }
}

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

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"] } }

我希望以打字的方式进行,但谓词翻译器不支持Enumerable.Select,这样就不会工作:

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);

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

1 个答案:

答案 0 :(得分: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);