Dave New
Dave New

Reputation: 40042

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.

Upvotes: 12

Views: 18423

Answers (2)

Ashley
Ashley

Reputation: 360

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

Upvotes: 14

Craig Wilson
Craig Wilson

Reputation: 12624

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.

Upvotes: 6

Related Questions