MongoDB FilterDefinition & IQueryable in C#
Asked Answered
B

2

12

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.

Bimanous answered 1/2, 2016 at 13:30 Comment(0)
S
6

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.

Streaky answered 1/2, 2016 at 13:59 Comment(2)
FYI, resolution fixed, status closedZoologist
Guys is there a solution to the thread question atm? Is it possible to include Filter inside a IQueryablePhotocurrent
J
14

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();
Jeffreyjeffreys answered 28/5, 2020 at 23:46 Comment(0)
S
6

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.

Streaky answered 1/2, 2016 at 13:59 Comment(2)
FYI, resolution fixed, status closedZoologist
Guys is there a solution to the thread question atm? Is it possible to include Filter inside a IQueryablePhotocurrent

© 2022 - 2024 — McMap. All rights reserved.