Search code examples
c#mongodbmongodb-.net-driver

MongoDb C# - How to store GeoJSON in a document


It is hard to find out GeoJSON in MongoDb C# Driver.

I try to create a document like this:

new BsonDocument()
{
    { "PointType", "Building"},
    { "Name", "My Place"},
    { "Location", ??? }
}

and try to fill in something like GeoJson.Point(new GeoJson2DCoordinates(0.0000, 0.0000)).ToBsonDocument() in the ??? above.

but once I create index for the Location and try to insert this document, MongoDb wan't happy. It throws location object expected, location array not in correct format.

Is there any sample or documentation for C# with BsonDocument and GeoJSON?

Any other suggestion to insert GeoJSON value?


Solution

  • I should use IndexKeys.Geo2DSphere instead of IndexKeys.Geo2D to store GeoJSON point.

    var keys = Builders<BsonDocument>.IndexKeys.Geo2DSphere("Location");
    await collection.Indexes.CreateOneAsync(keys);
    

    Then I can do:

    new BsonDocument()
    {
        { "PointType", "Building"},
        { "Name", "My Place"},
        { "Location", GeoJson.Point(new GeoJson2DCoordinates(lng, lat)).ToBsonDocument() }
    }