PorFavor
PorFavor

Reputation: 13

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.

Upvotes: 1

Views: 1484

Answers (2)

prasad_
prasad_

Reputation: 14287

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

Upvotes: 2

Dĵ ΝιΓΞΗΛψΚ
Dĵ ΝιΓΞΗΛψΚ

Reputation: 5669

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

Upvotes: 1

Related Questions