Search code examples
c#mongodbindexinggeospatialmongodb-.net-driver

C# MongoDB driver 2.4 - How to add a GeoSpatial index


I upgraded my MongoDB-C# driver, and I couldn't find information about how to create a GeoSpatial index. I have seen many posts using collection.EnsureIndex, but I don't have that available. I used to use the following, where 'collection' is IMongoCollection<>:

collection.CreateIndex((new IndexKeysBuilder().GeoSpatialSpherical("Location")));

What is the new way to do this?


Solution

  • I think this can help you:

    var index = Builders<YourCollectionClass>.IndexKeys.Geo2DSphere("Location");
    collection.Indexes.CreateOne(index);
    // or async version
    await collection.Indexes.CreateOneAsync(index);