简体   繁体   中英

Mongodb C# Driver Unsupported filter error with specific linq predicate

I have a IMongoCollection of contents:

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'] .

We defined, if I have entrypoint = 'ROOT' , it is equivalant that we have entrypoint of 'ROOT/1', 'ROOT2' too.

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.

But in my code, at runtime I have a mongodb error:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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