简体   繁体   English

Mongodb C# Driver Unsupported filter error with specific linq predicate

[英]Mongodb C# Driver Unsupported filter error with specific linq predicate

I have a IMongoCollection of contents:我有一个 IMongoCollection 内容:

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

now I want to filter my collections with userEntryPoints = ['ROOT', 'SPECIAL'] .现在我想用userEntryPoints = ['ROOT', 'SPECIAL']过滤我的 collections 。

We defined, if I have entrypoint = 'ROOT' , it is equivalant that we have entrypoint of 'ROOT/1', 'ROOT2' too.我们定义,如果我有entrypoint = 'ROOT' ,那么我们也有'ROOT/1', 'ROOT2'入口点。

So the expected result is所以预期的结果是

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

The code I am using is我正在使用的代码是

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

This should work if collection and userEntryPoints are simple array.如果collectionuserEntryPoints是简单的数组,这应该可以工作。

But in my code, at runtime I have a mongodb error:但是在我的代码中,在运行时我有一个 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)

What can I do to make such filtering possible?我该怎么做才能使这种过滤成为可能? Thank you.谢谢你。

This worked to return the two matching documents:这可以返回两个匹配的文档:

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

A variation:变体:

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

you can't do that with the driver.你不能对司机这样做。 it doesn't translate the StartsWith .它不翻译StartsWith it would only work with a simple equality check.它只适用于简单的平等检查。 here's how to get the result you want.这是获得所需结果的方法。 you need to convert your input to an array of prefixed regexes.您需要将输入转换为前缀正则表达式数组。 unfortunately there's no strongly typed way to do it.不幸的是,没有强类型的方法来做到这一点。

var userEntryPoints = "[/^ROOT/,/^SPECIAL/]";

FilterDefinition<Content> filter = $"{{ EntryPoint : {{ $in : {userEntryPoints} }} }}";

var result = await (await collection.FindAsync(filter)).ToListAsync();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM