【问题标题】:Mongodb C# Driver Unsupported filter error with specific linq predicateMongodb C# Driver Unsupported filter error with specific linq predicate
【发布时间】:2021-04-15 12:53:58
【问题描述】:

我有一个 IMongoCollection 内容:

collection = [
{Value = 'x', EntryPoint= 'ROOT/1' }, 
{Value = 'y', EntryPoint= 'ROOT/2' }, 
{Value = 'z', EntryPoint= 'OTHER/1' }]

现在我想过滤我的收藏 userEntryPoints = ['ROOT', 'SPECIAL'].

我们定义了,如果我有entrypoint = 'ROOT',那么我们也有'ROOT/1', 'ROOT2'的入口点。

所以预期的结果是

result = [
{Value = 'x', EntryPoint= 'ROOT/1' }, 
{Value = 'y', EntryPoint= 'ROOT/2' }]

我使用的代码是

var collection = mongoDatabase.GetCollection(Data);
return collection.AsQueryable().Select(xxx)
.Where(item => userEntryPoints.Any( entrypoint => item.EntryPoint.StartsWith(entrypoint)))

如果 collectionuserEntryPoints 是简单数组,这应该可以工作。

但在我的代码中,在运行时我有一个 mongodb 错误:

Unsupported filter: Any(value(System.Collections.Generic.List`1[System.String]].Where({document}{EntryPoint}.StarsWith(document))))

At MongoDB.Driver.Linq.Traslators.PredicateTranslator.Translate(Expression node)

我可以做些什么来使这种过滤成为可能? 谢谢。

【问题讨论】:

    标签: c# mongodb linq


    【解决方案1】:

    这可以返回两个匹配的文档:

    Regex regex = new Regex("^ROOT|^SPECIAL");
    var qry = collection.AsQueryable()
                        .Where<CollectonClass>(e => regex.IsMatch(e.EntryPoint))
                        .Select(e => new { e.Value, e.EntryPoint } );
    
    var docList = qry.ToList();
    docList.ForEach(e => Console.WriteLine(e.ToJson()));
    

    变体:

    var rgxList = new string [] { "^ROOT", "^SPECIAL" };
    var rgx = new Regex(string.Join("|", rgxList));
    var filter = Builders<BsonDocument>.Filter.Regex("EntryPoint", rgx);
    var list = collection.Find(filter).ToList<BsonDocument>();
    

    【讨论】:

    • 与 or 正则表达式相得益彰。不知道司机会翻译那个。干杯队友!
    【解决方案2】:

    您不能对驱动程序执行此操作。它不会翻译StartsWith。它只适用于简单的平等检查。这是获得所需结果的方法。您需要将输入转换为前缀正则表达式数组。不幸的是,没有强类型的方法来做到这一点。

    var userEntryPoints = "[/^ROOT/,/^SPECIAL/]";
    
    FilterDefinition<Content> filter = $"{{ EntryPoint : {{ $in : {userEntryPoints} }} }}";
    
    var result = await (await collection.FindAsync(filter)).ToListAsync();
    

    【讨论】:

      猜你喜欢
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      • 2022-11-08
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 2021-05-14
      • 1970-01-01
      相关资源
      最近更新 更多