@@ -51,6 +51,7 @@ import type {
5151 ClientEncryptionDataKeyProvider ,
5252 ClientEncryptionCreateDataKeyProviderOptions ,
5353 SearchIndexDescription ,
54+ ReadPreferenceMode ,
5455} from 'mongodb' ;
5556import ConnectionStringUrl from 'mongodb-connection-string-url' ;
5657import parseNamespace from 'mongodb-ns' ;
@@ -122,6 +123,12 @@ function isEmptyObject(obj: Record<string, unknown>) {
122123 return Object . keys ( obj ) . length === 0 ;
123124}
124125
126+ function isReadPreferenceSet ( connectionString : string ) : boolean {
127+ return ! ! new ConnectionStringUrl ( connectionString ) . searchParams . get (
128+ 'readPreference'
129+ ) ;
130+ }
131+
125132let id = 0 ;
126133
127134type ClientType = 'CRUD' | 'META' ;
@@ -661,7 +668,9 @@ export interface DataService {
661668 ns : string ,
662669 args ?: { query ?: Filter < Document > ; size ?: number ; fields ?: Document } ,
663670 options ?: AggregateOptions ,
664- executionOptions ?: ExecutionOptions
671+ executionOptions ?: ExecutionOptions & {
672+ fallbackReadPreference : ReadPreferenceMode ;
673+ }
665674 ) : Promise < Document [ ] > ;
666675
667676 /*** Insert ***/
@@ -2182,7 +2191,9 @@ class DataServiceImpl extends WithLogContext implements DataService {
21822191 fields,
21832192 } : { query ?: Filter < Document > ; size ?: number ; fields ?: Document } = { } ,
21842193 options : AggregateOptions = { } ,
2185- executionOptions ?: ExecutionOptions
2194+ executionOptions ?: ExecutionOptions & {
2195+ fallbackReadPreference ?: ReadPreferenceMode ;
2196+ }
21862197 ) : Promise < Document [ ] > {
21872198 const pipeline = [ ] ;
21882199 if ( query && Object . keys ( query ) . length > 0 ) {
@@ -2209,6 +2220,15 @@ class DataServiceImpl extends WithLogContext implements DataService {
22092220 pipeline ,
22102221 {
22112222 allowDiskUse : true ,
2223+ // When the read preference isn't set in the connection string explicitly,
2224+ // then we allow consumers to default to a read preference, for instance
2225+ // secondaryPreferred to avoid using the primary for analyzing documents.
2226+ ...( executionOptions ?. fallbackReadPreference &&
2227+ ! isReadPreferenceSet ( this . _connectionOptions . connectionString )
2228+ ? {
2229+ readPreference : executionOptions ?. fallbackReadPreference ,
2230+ }
2231+ : { } ) ,
22122232 ...options ,
22132233 } ,
22142234 executionOptions
0 commit comments