[CSHARP-2038] Can't Query/Index GeoJson Using Typed fields Created: 11/Sep/17  Updated: 27/Oct/23  Resolved: 09/Nov/22

Status: Closed
Project: C# Driver
Component/s: Serialization
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Peter Garafano (Inactive) Assignee: James Kovacs
Resolution: Works as Designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

if you have an object with a field of

public GeoJsonFeature<GeoJson2DGeographicCoordinates> Features { get; set; }

and you try to index on it, mongod requires the index to be on "Features.Geometry" but when you try to create an index definition on "Features.Geometry"

await Geography.Indexes.CreateManyAsync(new List<CreateIndexModel<GeoEntity>>
{
    new CreateIndexModel<GeoEntity>(Builders<GeoEntity>.IndexKeys.Geo2DSphere(x => x.Features.Geometry))
});

The driver throws an exception with a message that it can't determine serialization info for "Features.Geometry", if you try to create the index on just "Features", mongod blows up. if you manually create the index, like:

await Geography.Indexes.CreateManyAsync(new List<CreateIndexModel<GeoEntity>>
{
    new CreateIndexModel<GeoEntity>(Builders<GeoEntity>.IndexKeys.Geo2DSphere("features.geometry"))
});

It creates the Index OK.

If you now try to query, like

await Database.Geography.Find(Builders<GeoEntity>.Filter.NearSphere(x => x.Features.Geometry,
                location.Longitude, location.Latitude, 1600, 0)).ToListAsync();

it blows up, again unable to determine serialization information for "Features.Geometry"

but this query works just fine

var query = new BsonDocument("features.geometry",
    new BsonDocument("$geoNear",
        new BsonDocument("$geometry",
            new BsonDocument("type", "Point")
                .Add("coordinates", new BsonArray {location.Longitude, location.Latitude})).Add("$minDistance", 0).Add("$maxDistance", 1600)));
var possibleStates = await Database.Geography.Find(query).ToListAsync();



 Comments   
Comment by James Kovacs [ 09/Nov/22 ]

If you index/query the property rather than the contained geometry, then geo queries work as expected.

using System;
using MongoDB.Driver;
using MongoDB.Driver.GeoJsonObjectModel;
 
var client = new MongoClient();
var db = client.GetDatabase("test");
var coll = db.GetCollection<GeoEntity>("geoentities");
 
coll.Indexes.CreateOne(new CreateIndexModel<GeoEntity>(Builders<GeoEntity>.IndexKeys.Geo2DSphere(x => x.Features)));
 
var query = coll.Find(Builders<GeoEntity>.Filter.NearSphere(x => x.Features, 42, 42, 1600, 0));
Console.WriteLine(query);
foreach (var result in query.ToList())
{
    Console.WriteLine(result);
}
 
class GeoEntity
{
    public GeoJsonFeature<GeoJson2DGeographicCoordinates> Features { get; set; }
}

Generated at Wed Feb 07 21:41:26 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.