Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB FilterDefinition & IQueryable in C#

I have the following spatial FilterDefinition:

var filter = Builders<MyDocument>
                .Filter
                .Near(x => x.Point, point, 1000);

Is there any way to include this into an IQueryable expression?

For example, I might have the following LINQ statement. How can I include the above condition? From what I can see, there is no LINQ support for spatial querying.

return Database
    .GetCollection<Places>("Places")
    .AsQueryable()
    .Where(x => x.StartDate.Date <= date)
    .Where(x => x.EndDate.Date >= date)
    .Where(x => keys.Contains(selectedKeys))
    .ToList();

I am using the new 2.2.2 libraries.

like image 769
Dave New Avatar asked Feb 01 '16 13:02

Dave New


2 Answers

As of 2.4, you can use Inject() to accomplish this.

See: https://mongodb.github.io/mongo-csharp-driver/2.4/apidocs/html/M_MongoDB_Driver_Linq_LinqExtensions_Inject__1.htm

With the example code provided (corrected slightly) this would be:

var filter = Builders<Places>
                .Filter
                .Near(x => x.Point, point, 1000);

return Database
    .GetCollection<Places>("Places")
    .AsQueryable()
    .Where(x => x.StartDate.Date <= date)
    .Where(x => x.EndDate.Date >= date)
    .Where(x => keys.Contains(selectedKeys))
    .Where(x => filter.Inject())
    .ToList();
like image 86
Ashley Avatar answered Sep 23 '22 15:09

Ashley


There is a feature request in the .NET drivers jira project: https://jira.mongodb.org/browse/CSHARP-1445. So, the answer is currently no, but hopefully soon.

However, there is a "Where" method on the FilterDefinitionBuilder (https://github.com/mongodb/mongo-csharp-driver/blob/master/src/MongoDB.Driver/FilterDefinitionBuilder.cs#L1286) that will allow you to include a LINQ predicate into normal find/aggregation queries.

like image 22
Craig Wilson Avatar answered Sep 22 '22 15:09

Craig Wilson