How to make the following Entity framework query in MongoDB C# driver?
Get all objects that contains all keywords from the filter - in its name property
var keywords = filter.Split(' ');
_context.Businesses
.Where(b => keywords.All(s=>b.Name.Contains(s)))
.ToList();
I've tried to excute the same query on mongo but I get that the filter is unsupported
_collection.Find<Business>(b => keywords.All(s => b.Name.Contains(s))).ToList();
The exception
An exception of type 'System.ArgumentException' occurred in MongoDB.Driver.dll but was not handled in user code Additional information: Unsupported filter: All(value(System.String[]).Where({document}{Name}.Contains({document}))).
Solution
I've changed the query as M.Wiśnicki suggested
return _collection.AsQueryable<Business>().AsEnumerable().Where(b => keywords.All(keyword => b.Name.Contains(keyword))).ToList();
Proposed answer will be ok, but this way you get all data to client, the query could be executed directly on MongoDB:
var results = _collection.Find(Builders<Business>.Filter.Not(
Builders<Business>.Filter.ElemMatch(
x=>x.keywords,
k=>!k.Name.Contains(s))));
It's a little bit tricky, because we filter all values that not (not contain s), but it works.
If you don't have a huge amount of data it's ok to query Enumerable as already proposed.
In MongoDB you need use strongly-typed collection when you call LINQ queries. So need to use AsEnumerable(), this return output as IEnumerable<out T> and you will be able use LINQ. Your query should look like
var results = Businesses.AsEnumerable().Select(x => x.ToLower())
.Where(x => keywords.All(x.Contains));