1

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.

2 Answers 2

2

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>();
Sign up to request clarification or add additional context in comments.

1 Comment

good one with the or regex. didn't know the driver could translate that. cheers mate!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.