Search code examples
mongodbmongodb-.net-driver

Index hint with mongodb csharp


I am migrating from the mongodb csharp driver 1.10.0 to 2.0.0. One of the collection I am using is very big and has to fulfill many queries with different filter attributes. That is why I was relying on some index hint statements. With the v1.10 driver it looks like

 myCollection.Find(query).SetHint("myIndexName");

I searched the v2 driver api but this hint method seems to be completly removed in the v2 driver. Is there an alternative? How should I do index hints with the v2 driver?

Note: The Solutions provided works for latest mongodb csharp drivers as well


Solution

  • You can use the FindOptions.Modifiers property.

    var modifiers = new BsonDocument("$hint", "myIndexName"); 
    await myCollection.Find(query, new FindOptions { Modifiers = modifiers }).ToListAsync();
    

    May I ask why you are using the hint? Was the server consistently choosing the wrong index? You shouldn't need to do this except in exceptional cases.

    Craig