user1202839
user1202839

Reputation: 375

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?

Upvotes: 1

Views: 990

Answers (2)

Danil
Danil

Reputation: 895

  IndexKeysDefinition<DBGeoObject> keys = "{ location: \"2dsphere\" }";
  var indexModel = new CreateIndexModel<DBGeoObject>(keys);

  _geoCollection.Indexes.CreateOneAsync(indexModel);

You'll have as a result:

enter image description here

Upvotes: 0

shA.t
shA.t

Reputation: 16958

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

Upvotes: 3

Related Questions