Search code examples
c#mongodbmongodb-querymongodb-.net-drivermongodb-csharp-2.0

How do you set the readPreference for a single query against mongo using the c# driver


I have an application using a number of different mongo databases and 99% of the time it needs to read from the primary of the replica set but I have a couple reporting queries that pull back a lot of data and are not covered by indexes and I would like them to run against a secondary. Is there any way to specify for a single query that it should have a read preference of secondary. I am wanting to avoid having more connection strings as I already have near a dozen in the application.


Solution

  • There are a couple of WithXXX methods on the collection for this very purpose.

    collection.WithReadPreference(ReadPreference.SecondaryPreferred).Find(...)