【问题标题】:Strongly typed query on nested field using MongoDB C# driver 2.2使用 MongoDB C# 驱动程序 2.2 对嵌套字段进行强类型查询
【发布时间】:2016-05-10 05:16:31
【问题描述】:

考虑以下结构

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# arrays mongodb mongodb-query mongodb-.net-driver


【解决方案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);

【讨论】:

    猜你喜欢
    • 2017-08-08
    • 2020-08-08
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 2016-11-16
    • 2018-11-16
    • 1970-01-01
    • 2016-05-15
    相关资源
    最近更新 更多