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

Strongly typed query on nested field using MongoDB C# driver 2.2

提问人:newbie 提问时间:2/2/2016 更新时间:8/25/2016 访问量:475

问:

请考虑以下结构

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

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

C# 数组 mongodb 查询 mongodb -.net-driver

评论

1赞 jimfromthegym - Jim Mackin 3/24/2016
你有没有想过这一点?我需要做类似的事情......

答:

0赞 andrei.ciprian 8/25/2016 #1
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);