This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch CAMEL-27193
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 07f60b29ba2ae656158fc54c4eed0d18f310fc0f
Author: Claus Ibsen <[email protected]>
AuthorDate: Sat Nov 21 10:05:54 2026 +0100

    CAMEL-27193: camel-mongodb - readPreference and the other client options 
are applied to the client created from hosts or connectionUriString
    
    The endpoint built its MongoClientSettings from the connection string and
    the TLS options only. replicaSet, readPreference, readPreferenceTags,
    maxStalenessSeconds, appName, compressors, zlibCompressionLevel, the
    timeouts, the pool sizes, srvServiceName, srvMaxHosts, retryWrites,
    retryReads, directConnection and loadBalanced were never used.
    
    They are now applied on top of the connection string when they differ from
    their default, so the same option in connectionUriString is kept when the
    endpoint leaves it at its default. The documented readPreference values
    PRIMARY_PREFERRED and SECONDARY_PREFERRED are accepted. An endpoint whose
    client it did not create (mongoConnection, component, registry) logs a WARN
    with the options it cannot apply.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    Signed-off-by: Claus Ibsen <[email protected]>
---
 .../apache/camel/catalog/components/mongodb.json   |   2 +-
 components/camel-mongodb/pom.xml                   |   5 +
 .../apache/camel/component/mongodb/mongodb.json    |   2 +-
 .../src/main/docs/mongodb-component.adoc           |  23 ++
 .../camel/component/mongodb/MongoDbEndpoint.java   | 248 +++++++++++++++++-
 .../mongodb/MongoDbEndpointClientOptionsTest.java  | 281 +++++++++++++++++++++
 .../integration/MongoDbClientOptionsIT.java        |  79 ++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |  23 ++
 .../dsl/MongoDbEndpointBuilderFactory.java         |  27 +-
 9 files changed, 669 insertions(+), 21 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/mongodb.json
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/mongodb.json
index 802ed5605b89..01189256370b 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/mongodb.json
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/mongodb.json
@@ -104,7 +104,7 @@
     "maxStalenessSeconds": { "index": 37, "kind": "parameter", "displayName": 
"Max Staleness Seconds", "group": "advanced", "label": "advanced", "required": 
false, "type": "integer", "javaType": "java.lang.Integer", "deprecated": false, 
"autowired": false, "secret": false, "defaultValue": -1, "description": 
"Specifies, in seconds, how stale a secondary can be before the driver stops 
communicating with that secondary. The minimum value is either 90 seconds or 
the heartbeat frequency plus  [...]
     "minPoolSize": { "index": 38, "kind": "parameter", "displayName": "Min 
Pool Size", "group": "advanced", "label": "advanced", "required": false, 
"type": "integer", "javaType": "java.lang.Integer", "deprecated": false, 
"autowired": false, "secret": false, "defaultValue": 0, "description": 
"Specifies the minimum number of connections that must exist at any moment in a 
single connection pool. Default: 0" },
     "readPreference": { "index": 39, "kind": "parameter", "displayName": "Read 
Preference", "group": "advanced", "label": "advanced", "required": false, 
"type": "enum", "javaType": "java.lang.String", "enum": [ "PRIMARY", 
"PRIMARY_PREFERRED", "SECONDARY", "SECONDARY_PREFERRED", "NEAREST" ], 
"deprecated": false, "autowired": false, "secret": false, "defaultValue": 
"PRIMARY", "description": "Configure how MongoDB clients route read operations 
to the members of a replica set. Possible value [...]
-    "readPreferenceTags": { "index": 40, "kind": "parameter", "displayName": 
"Read Preference Tags", "group": "advanced", "label": "advanced", "required": 
false, "type": "string", "javaType": "java.lang.String", "deprecated": false, 
"autowired": false, "secret": false, "description": "A representation of a tag 
set as a comma-separated list of colon-separated key-value pairs, e.g. 
dc:ny,rack:1. Spaces are stripped from the beginning and end of all keys and 
values. To specify a list of tag [...]
+    "readPreferenceTags": { "index": 40, "kind": "parameter", "displayName": 
"Read Preference Tags", "group": "advanced", "label": "advanced", "required": 
false, "type": "string", "javaType": "java.lang.String", "deprecated": false, 
"autowired": false, "secret": false, "description": "A representation of a tag 
set as a comma-separated list of colon-separated key-value pairs, e.g. 
dc:ny,rack:1. Spaces are stripped from the beginning and end of all keys and 
values. To specify a list of tag [...]
     "replicaSet": { "index": 41, "kind": "parameter", "displayName": "Replica 
Set", "group": "advanced", "label": "advanced", "required": false, "type": 
"string", "javaType": "java.lang.String", "deprecated": false, "autowired": 
false, "secret": false, "description": "Specifies that the connection string 
provided includes multiple hosts. When specified, the driver attempts to find 
all members of that set." },
     "retryReads": { "index": 42, "kind": "parameter", "displayName": "Retry 
Reads", "group": "advanced", "label": "advanced", "required": false, "type": 
"boolean", "javaType": "boolean", "deprecated": false, "autowired": false, 
"secret": false, "defaultValue": true, "description": "Specifies that the 
driver must retry supported read operations if they fail due to a network 
error. Default: true" },
     "retryWrites": { "index": 43, "kind": "parameter", "displayName": "Retry 
Writes", "group": "advanced", "label": "advanced", "required": false, "type": 
"boolean", "javaType": "boolean", "deprecated": false, "autowired": false, 
"secret": false, "defaultValue": true, "description": "Specifies that the 
driver must retry supported write operations if they fail due to a network 
error. Default: true" },
diff --git a/components/camel-mongodb/pom.xml b/components/camel-mongodb/pom.xml
index 5bf02f2c819e..5b57b8b1e973 100644
--- a/components/camel-mongodb/pom.xml
+++ b/components/camel-mongodb/pom.xml
@@ -104,6 +104,11 @@
             <scope>test</scope>
         </dependency>
 
+        <dependency>
+            <groupId>org.assertj</groupId>
+            <artifactId>assertj-core</artifactId>
+            <scope>test</scope>
+        </dependency>
         <dependency>
             <groupId>org.mockito</groupId>
             <artifactId>mockito-core</artifactId>
diff --git 
a/components/camel-mongodb/src/generated/resources/META-INF/org/apache/camel/component/mongodb/mongodb.json
 
b/components/camel-mongodb/src/generated/resources/META-INF/org/apache/camel/component/mongodb/mongodb.json
index 802ed5605b89..01189256370b 100644
--- 
a/components/camel-mongodb/src/generated/resources/META-INF/org/apache/camel/component/mongodb/mongodb.json
+++ 
b/components/camel-mongodb/src/generated/resources/META-INF/org/apache/camel/component/mongodb/mongodb.json
@@ -104,7 +104,7 @@
     "maxStalenessSeconds": { "index": 37, "kind": "parameter", "displayName": 
"Max Staleness Seconds", "group": "advanced", "label": "advanced", "required": 
false, "type": "integer", "javaType": "java.lang.Integer", "deprecated": false, 
"autowired": false, "secret": false, "defaultValue": -1, "description": 
"Specifies, in seconds, how stale a secondary can be before the driver stops 
communicating with that secondary. The minimum value is either 90 seconds or 
the heartbeat frequency plus  [...]
     "minPoolSize": { "index": 38, "kind": "parameter", "displayName": "Min 
Pool Size", "group": "advanced", "label": "advanced", "required": false, 
"type": "integer", "javaType": "java.lang.Integer", "deprecated": false, 
"autowired": false, "secret": false, "defaultValue": 0, "description": 
"Specifies the minimum number of connections that must exist at any moment in a 
single connection pool. Default: 0" },
     "readPreference": { "index": 39, "kind": "parameter", "displayName": "Read 
Preference", "group": "advanced", "label": "advanced", "required": false, 
"type": "enum", "javaType": "java.lang.String", "enum": [ "PRIMARY", 
"PRIMARY_PREFERRED", "SECONDARY", "SECONDARY_PREFERRED", "NEAREST" ], 
"deprecated": false, "autowired": false, "secret": false, "defaultValue": 
"PRIMARY", "description": "Configure how MongoDB clients route read operations 
to the members of a replica set. Possible value [...]
-    "readPreferenceTags": { "index": 40, "kind": "parameter", "displayName": 
"Read Preference Tags", "group": "advanced", "label": "advanced", "required": 
false, "type": "string", "javaType": "java.lang.String", "deprecated": false, 
"autowired": false, "secret": false, "description": "A representation of a tag 
set as a comma-separated list of colon-separated key-value pairs, e.g. 
dc:ny,rack:1. Spaces are stripped from the beginning and end of all keys and 
values. To specify a list of tag [...]
+    "readPreferenceTags": { "index": 40, "kind": "parameter", "displayName": 
"Read Preference Tags", "group": "advanced", "label": "advanced", "required": 
false, "type": "string", "javaType": "java.lang.String", "deprecated": false, 
"autowired": false, "secret": false, "description": "A representation of a tag 
set as a comma-separated list of colon-separated key-value pairs, e.g. 
dc:ny,rack:1. Spaces are stripped from the beginning and end of all keys and 
values. To specify a list of tag [...]
     "replicaSet": { "index": 41, "kind": "parameter", "displayName": "Replica 
Set", "group": "advanced", "label": "advanced", "required": false, "type": 
"string", "javaType": "java.lang.String", "deprecated": false, "autowired": 
false, "secret": false, "description": "Specifies that the connection string 
provided includes multiple hosts. When specified, the driver attempts to find 
all members of that set." },
     "retryReads": { "index": 42, "kind": "parameter", "displayName": "Retry 
Reads", "group": "advanced", "label": "advanced", "required": false, "type": 
"boolean", "javaType": "boolean", "deprecated": false, "autowired": false, 
"secret": false, "defaultValue": true, "description": "Specifies that the 
driver must retry supported read operations if they fail due to a network 
error. Default: true" },
     "retryWrites": { "index": 43, "kind": "parameter", "displayName": "Retry 
Writes", "group": "advanced", "label": "advanced", "required": false, "type": 
"boolean", "javaType": "boolean", "deprecated": false, "autowired": false, 
"secret": false, "defaultValue": true, "description": "Specifies that the 
driver must retry supported write operations if they fail due to a network 
error. Default: true" },
diff --git a/components/camel-mongodb/src/main/docs/mongodb-component.adoc 
b/components/camel-mongodb/src/main/docs/mongodb-component.adoc
index b8df7924241d..2c1b68aeaa93 100644
--- a/components/camel-mongodb/src/main/docs/mongodb-component.adoc
+++ b/components/camel-mongodb/src/main/docs/mongodb-component.adoc
@@ -75,6 +75,29 @@ own client and connection pool, and closes it when it stops 
(for example when it
 the CamelContext stops). The endpoint never closes a client it did not create. 
To share one client between endpoints,
 bind a `MongoClient` and have the endpoints use it instead of 
`connectionUriString` or `hosts`.
 
+=== Client options
+
+The client options of the endpoint (`replicaSet`, `readPreference`, 
`readPreferenceTags`, `maxStalenessSeconds`,
+`appName`, `compressors`, `zlibCompressionLevel`, `connectTimeoutMS`, 
`socketTimeoutMS`, `serverSelectionTimeoutMS`,
+`localThresholdMS`, `heartbeatFrequencyMS`, `maxIdleTimeMS`, `maxLifeTimeMS`, 
`minPoolSize`, `maxPoolSize`,
+`maxConnecting`, `waitQueueTimeoutMS`, `srvServiceName`, `srvMaxHosts`, 
`retryWrites`, `retryReads`, `directConnection`
+and `loadBalanced`) configure the client the endpoint creates from `hosts` or 
`connectionUriString`. For example, a
+tailable consumer that reads from the secondaries of a replica set:
+
+----
+mongodb:dummy?hosts=host1:27017,host2:27017,host3:27017&replicaSet=rs0&readPreference=SECONDARY&database=shop&collection=events&consumerType=tailable&tailTrackIncreasingField=seq
+----
+
+An option is applied only when its value differs from its default, and then it 
overrides the same option in
+`connectionUriString`. An option left at its default keeps the value of the 
connection string, so
+`connectionUriString=RAW(mongodb://host/?readPreference=nearest)` reads from 
the nearest member. The read preference is
+made of `readPreference`, `readPreferenceTags` and `maxStalenessSeconds` 
together: when any of them is set, the three
+replace the read preference of the connection string.
+
+These options cannot change a `MongoClient` the endpoint did not create (set 
with `mongoConnection`, on the component,
+or from the registry). Configure such a client with its own 
`MongoClientSettings`. In that case the endpoint logs a WARN
+that lists the options it does not use.
+
 // component options: START
 include::partial$component-configure-options.adoc[]
 include::partial$component-endpoint-options.adoc[]
diff --git 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java
 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java
index 3fd8daa1ed16..b7197d9705e2 100644
--- 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java
+++ 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbEndpoint.java
@@ -21,20 +21,26 @@ import java.security.GeneralSecurityException;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map;
+import java.util.concurrent.TimeUnit;
 import java.util.stream.StreamSupport;
 
 import javax.net.ssl.SSLContext;
 
 import com.mongodb.ConnectionString;
 import com.mongodb.MongoClientSettings;
+import com.mongodb.MongoCompressor;
 import com.mongodb.ReadPreference;
+import com.mongodb.Tag;
+import com.mongodb.TagSet;
 import com.mongodb.WriteConcern;
 import com.mongodb.client.MongoClient;
 import com.mongodb.client.MongoClients;
 import com.mongodb.client.MongoCollection;
 import com.mongodb.client.MongoDatabase;
 import com.mongodb.client.model.changestream.FullDocument;
+import com.mongodb.connection.ClusterConnectionMode;
 import org.apache.camel.Category;
 import org.apache.camel.Consumer;
 import org.apache.camel.Processor;
@@ -127,6 +133,15 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
 
     private static final Logger LOG = 
LoggerFactory.getLogger(MongoDbEndpoint.class);
 
+    // the defaults of the client options, the same as the defaults of the 
MongoDB driver
+    private static final int DEFAULT_SERVER_SELECTION_TIMEOUT_MS = 30000;
+    private static final int DEFAULT_LOCAL_THRESHOLD_MS = 15;
+    private static final int DEFAULT_CONNECT_TIMEOUT_MS = 10000;
+    private static final int DEFAULT_MAX_POOL_SIZE = 100;
+    private static final int DEFAULT_MAX_CONNECTING = 2;
+    private static final int DEFAULT_WAIT_QUEUE_TIMEOUT_MS = 120000;
+    private static final int DEFAULT_MAX_STALENESS_SECONDS = -1;
+
     @UriParam(description = "Sets the connection bean used as a client for 
connecting to a database.")
     private MongoClient mongoConnection;
 
@@ -183,9 +198,9 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
     private MongoDbOutputType outputType;
     //Server Selection Configuration
     @UriParam(label = "advanced", defaultValue = "30000")
-    private Integer serverSelectionTimeoutMS = 30000;
+    private Integer serverSelectionTimeoutMS = 
DEFAULT_SERVER_SELECTION_TIMEOUT_MS;
     @UriParam(label = "advanced", defaultValue = "15")
-    private Integer localThresholdMS = 15;
+    private Integer localThresholdMS = DEFAULT_LOCAL_THRESHOLD_MS;
     //Server Monitoring Configuration
     @UriParam(label = "advanced")
     private Integer heartbeatFrequencyMS;
@@ -200,7 +215,7 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
     @UriParam(label = "security")
     private SSLContextParameters sslContextParameters;
     @UriParam(label = "advanced", defaultValue = "10000")
-    private Integer connectTimeoutMS = 10000;
+    private Integer connectTimeoutMS = DEFAULT_CONNECT_TIMEOUT_MS;
     @UriParam(label = "advanced", defaultValue = "0")
     private Integer socketTimeoutMS = 0;
     @UriParam(label = "advanced", defaultValue = "0")
@@ -211,11 +226,11 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
     @UriParam(label = "advanced", defaultValue = "0")
     private Integer minPoolSize = 0;
     @UriParam(label = "advanced", defaultValue = "100")
-    private Integer maxPoolSize = 100;
+    private Integer maxPoolSize = DEFAULT_MAX_POOL_SIZE;
     @UriParam(label = "advanced", defaultValue = "2")
-    private Integer maxConnecting = 2;
+    private Integer maxConnecting = DEFAULT_MAX_CONNECTING;
     @UriParam(label = "advanced", defaultValue = "120000")
-    private Integer waitQueueTimeoutMS = 120000;
+    private Integer waitQueueTimeoutMS = DEFAULT_WAIT_QUEUE_TIMEOUT_MS;
     //Write concern
     @UriParam(label = "advanced", defaultValue = "ACKNOWLEDGED",
               enums = 
"ACKNOWLEDGED,W1,W2,W3,UNACKNOWLEDGED,JOURNALED,MAJORITY")
@@ -228,7 +243,7 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
     @UriParam(label = "advanced")
     private String readPreferenceTags;
     @UriParam(label = "advanced", defaultValue = "-1")
-    private Integer maxStalenessSeconds = -1;
+    private Integer maxStalenessSeconds = DEFAULT_MAX_STALENESS_SECONDS;
     //Server Handshake configuration
     @UriParam(label = "advanced")
     private String appName;
@@ -508,6 +523,15 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
         } else {
             LOG.debug("Resolved the connection provided by mongoConnection 
property parameter as {}", mongoConnection);
         }
+        if (createdMongoConnection == null) {
+            List<String> ignored = getClientOptionsSet();
+            if (!ignored.isEmpty()) {
+                LOG.warn("The options {} of {} are not used: they apply only 
to a client the endpoint creates from hosts"
+                         + " or connectionUriString, not to a MongoClient set 
with mongoConnection, on the component or"
+                         + " from the registry. Configure that MongoClient 
instead.",
+                        ignored, getEndpointBaseUri());
+            }
+        }
         super.doStart();
     }
 
@@ -566,8 +590,9 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
             connectionUri = String.format("mongodb://%s%s%s", credentials, 
hosts, connectionOptions);
         }
 
+        ConnectionString connectionString = new 
ConnectionString(connectionUri);
         MongoClientSettings.Builder builder = MongoClientSettings.builder()
-                .applyConnectionString(new ConnectionString(connectionUri));
+                .applyConnectionString(connectionString);
 
         SSLContext sslContext = createSslContext();
         if (tls || sslContext != null || tlsAllowInvalidHostnames) {
@@ -583,9 +608,200 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
                 }
             });
         }
+        applyClientOptions(builder, connectionString);
         return builder.build();
     }
 
+    /**
+     * Applies the client options of the endpoint (replicaSet, readPreference, 
the timeouts, the pool sizes, appName,
+     * compressors and so on) on top of the connection string. An option is 
applied only when its value differs from its
+     * default, so the same option in connectionUriString is kept when the 
endpoint does not change it.
+     */
+    private void applyClientOptions(MongoClientSettings.Builder builder, 
ConnectionString connectionString) {
+        builder.applyToClusterSettings(cluster -> {
+            if (isSet(replicaSet, null)) {
+                cluster.requiredReplicaSetName(replicaSet);
+            }
+            if (isSet(serverSelectionTimeoutMS, 
DEFAULT_SERVER_SELECTION_TIMEOUT_MS)) {
+                cluster.serverSelectionTimeout(serverSelectionTimeoutMS, 
TimeUnit.MILLISECONDS);
+            }
+            if (isSet(localThresholdMS, DEFAULT_LOCAL_THRESHOLD_MS)) {
+                cluster.localThreshold(localThresholdMS, 
TimeUnit.MILLISECONDS);
+            }
+            if (isSet(srvServiceName, null)) {
+                cluster.srvServiceName(srvServiceName);
+            }
+            if (isSet(srvMaxHosts, null)) {
+                cluster.srvMaxHosts(srvMaxHosts);
+            }
+            if (loadBalanced) {
+                cluster.mode(ClusterConnectionMode.LOAD_BALANCED);
+            } else if (directConnection) {
+                cluster.mode(ClusterConnectionMode.SINGLE);
+            }
+        });
+        if (isSet(heartbeatFrequencyMS, null)) {
+            builder.applyToServerSettings(
+                    server -> server.heartbeatFrequency(heartbeatFrequencyMS, 
TimeUnit.MILLISECONDS));
+        }
+        builder.applyToSocketSettings(socket -> {
+            if (isSet(connectTimeoutMS, DEFAULT_CONNECT_TIMEOUT_MS)) {
+                socket.connectTimeout(connectTimeoutMS, TimeUnit.MILLISECONDS);
+            }
+            if (isSet(socketTimeoutMS, 0)) {
+                socket.readTimeout(socketTimeoutMS, TimeUnit.MILLISECONDS);
+            }
+        });
+        builder.applyToConnectionPoolSettings(pool -> {
+            if (isSet(maxIdleTimeMS, 0)) {
+                pool.maxConnectionIdleTime(maxIdleTimeMS, 
TimeUnit.MILLISECONDS);
+            }
+            if (isSet(maxLifeTimeMS, 0)) {
+                pool.maxConnectionLifeTime(maxLifeTimeMS, 
TimeUnit.MILLISECONDS);
+            }
+            if (isSet(minPoolSize, 0)) {
+                pool.minSize(minPoolSize);
+            }
+            if (isSet(maxPoolSize, DEFAULT_MAX_POOL_SIZE)) {
+                pool.maxSize(maxPoolSize);
+            }
+            if (isSet(maxConnecting, DEFAULT_MAX_CONNECTING)) {
+                pool.maxConnecting(maxConnecting);
+            }
+            if (isSet(waitQueueTimeoutMS, DEFAULT_WAIT_QUEUE_TIMEOUT_MS)) {
+                pool.maxWaitTime(waitQueueTimeoutMS, TimeUnit.MILLISECONDS);
+            }
+        });
+        if (isReadPreferenceSet()) {
+            builder.readPreference(createReadPreference());
+        }
+        if (isSet(appName, null)) {
+            builder.applicationName(appName);
+        }
+        if (isSet(compressors, null) || isSet(zlibCompressionLevel, null)) {
+            List<MongoCompressor> list = isSet(compressors, null)
+                    ? createCompressors(compressors) : 
connectionString.getCompressorList();
+            if (isSet(zlibCompressionLevel, null)) {
+                list = list.stream()
+                        .map(c -> "zlib".equals(c.getName())
+                                ? c.withProperty(MongoCompressor.LEVEL, 
zlibCompressionLevel) : c)
+                        .toList();
+            }
+            builder.compressorList(list);
+        }
+        if (!retryWrites) {
+            builder.retryWrites(false);
+        }
+        if (!retryReads) {
+            builder.retryReads(false);
+        }
+    }
+
+    private static boolean isSet(Object value, Object defaultValue) {
+        return value != null && !value.equals(defaultValue);
+    }
+
+    private boolean isReadPreferenceSet() {
+        return readPreference != null && 
!"PRIMARY".equalsIgnoreCase(readPreference) || isSet(readPreferenceTags, null)
+                || isSet(maxStalenessSeconds, DEFAULT_MAX_STALENESS_SECONDS);
+    }
+
+    /**
+     * The read preference made of the readPreference, readPreferenceTags and 
maxStalenessSeconds options.
+     */
+    ReadPreference createReadPreference() {
+        String name = getReadPreferenceBean().getName();
+        List<TagSet> tagSets = parseReadPreferenceTags(readPreferenceTags);
+        if (isSet(maxStalenessSeconds, DEFAULT_MAX_STALENESS_SECONDS)) {
+            return ReadPreference.valueOf(name, tagSets, maxStalenessSeconds, 
TimeUnit.SECONDS);
+        }
+        return tagSets.isEmpty() ? ReadPreference.valueOf(name) : 
ReadPreference.valueOf(name, tagSets);
+    }
+
+    /**
+     * Parses tag sets separated by semicolons, each a comma separated list of 
colon separated key-value pairs, for
+     * example {@code dc:ny,rack:1;dc:ny;} (an empty tag set matches any 
member). Each tag set may also be written as
+     * {@code readPreferenceTags=dc:ny}, as in a connection string.
+     */
+    static List<TagSet> parseReadPreferenceTags(String value) {
+        List<TagSet> answer = new ArrayList<>();
+        if (ObjectHelper.isEmpty(value)) {
+            return answer;
+        }
+        for (String part : value.split(";", -1)) {
+            String tagSet = part.trim();
+            if (tagSet.startsWith("readPreferenceTags=")) {
+                tagSet = 
tagSet.substring("readPreferenceTags=".length()).trim();
+            }
+            List<Tag> tags = new ArrayList<>();
+            if (!tagSet.isEmpty()) {
+                for (String pair : tagSet.split(",")) {
+                    int pos = pair.indexOf(':');
+                    if (pos <= 0) {
+                        throw new IllegalArgumentException(
+                                "The tag " + pair + " in readPreferenceTags 
must be written as key:value");
+                    }
+                    tags.add(new Tag(pair.substring(0, pos).trim(), 
pair.substring(pos + 1).trim()));
+                }
+            }
+            answer.add(new TagSet(tags));
+        }
+        return answer;
+    }
+
+    private static List<MongoCompressor> createCompressors(String value) {
+        List<MongoCompressor> answer = new ArrayList<>();
+        for (String name : value.split(",")) {
+            switch (name.trim().toLowerCase(Locale.ROOT)) {
+                case "zlib" -> 
answer.add(MongoCompressor.createZlibCompressor());
+                case "snappy" -> 
answer.add(MongoCompressor.createSnappyCompressor());
+                case "zstd" -> 
answer.add(MongoCompressor.createZstdCompressor());
+                default -> throw new IllegalArgumentException(
+                        "Unsupported compressor " + name + " in compressors, 
use zlib, snappy or zstd");
+            }
+        }
+        return answer;
+    }
+
+    /**
+     * The client options set on this endpoint, which are applied only to a 
client the endpoint creates from hosts or
+     * connectionUriString.
+     */
+    List<String> getClientOptionsSet() {
+        List<String> answer = new ArrayList<>();
+        addIfSet(answer, "replicaSet", replicaSet, null);
+        addIfSet(answer, "serverSelectionTimeoutMS", serverSelectionTimeoutMS, 
DEFAULT_SERVER_SELECTION_TIMEOUT_MS);
+        addIfSet(answer, "localThresholdMS", localThresholdMS, 
DEFAULT_LOCAL_THRESHOLD_MS);
+        addIfSet(answer, "heartbeatFrequencyMS", heartbeatFrequencyMS, null);
+        addIfSet(answer, "srvServiceName", srvServiceName, null);
+        addIfSet(answer, "srvMaxHosts", srvMaxHosts, null);
+        addIfSet(answer, "loadBalanced", loadBalanced, false);
+        addIfSet(answer, "directConnection", directConnection, false);
+        addIfSet(answer, "connectTimeoutMS", connectTimeoutMS, 
DEFAULT_CONNECT_TIMEOUT_MS);
+        addIfSet(answer, "socketTimeoutMS", socketTimeoutMS, 0);
+        addIfSet(answer, "maxIdleTimeMS", maxIdleTimeMS, 0);
+        addIfSet(answer, "maxLifeTimeMS", maxLifeTimeMS, 0);
+        addIfSet(answer, "minPoolSize", minPoolSize, 0);
+        addIfSet(answer, "maxPoolSize", maxPoolSize, DEFAULT_MAX_POOL_SIZE);
+        addIfSet(answer, "maxConnecting", maxConnecting, 
DEFAULT_MAX_CONNECTING);
+        addIfSet(answer, "waitQueueTimeoutMS", waitQueueTimeoutMS, 
DEFAULT_WAIT_QUEUE_TIMEOUT_MS);
+        if (isReadPreferenceSet()) {
+            answer.add("readPreference");
+        }
+        addIfSet(answer, "appName", appName, null);
+        addIfSet(answer, "compressors", compressors, null);
+        addIfSet(answer, "zlibCompressionLevel", zlibCompressionLevel, null);
+        addIfSet(answer, "retryWrites", retryWrites, true);
+        addIfSet(answer, "retryReads", retryReads, true);
+        return answer;
+    }
+
+    private static void addIfSet(List<String> answer, String name, Object 
value, Object defaultValue) {
+        if (isSet(value, defaultValue)) {
+            answer.add(name);
+        }
+    }
+
     private SSLContext createSslContext() {
         if (sslContextParameters == null) {
             return null;
@@ -923,8 +1139,13 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
     }
 
     public ReadPreference getReadPreferenceBean() {
+        if (readPreference == null) {
+            return ReadPreference.primary();
+        }
+        // PRIMARY_PREFERRED and SECONDARY_PREFERRED are the documented 
values, the driver knows them without the
+        // underscore (primaryPreferred, secondaryPreferred), case-insensitive
         // will throw an IllegalArgumentException if the input is incorrect
-        return ReadPreference.valueOf(getReadPreference());
+        return ReadPreference.valueOf(readPreference.replace("_", ""));
     }
 
     public String getUsername() {
@@ -1158,10 +1379,11 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
 
     /**
      * A representation of a tag set as a comma-separated list of 
colon-separated key-value pairs, e.g. "dc:ny,rack:1".
-     * Spaces are stripped from the beginning and end of all keys and values. 
To specify a list of tag sets, using
-     * multiple readPreferenceTags, e.g., 
readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags=
-     * Note the empty value for the last one, which means match any secondary 
as a last resort. Order matters when using
-     * multiple readPreferenceTags.
+     * Spaces are stripped from the beginning and end of all keys and values. 
To specify a list of tag sets, separate
+     * them with semicolons, e.g. "dc:ny,rack:1;dc:ny;" (the form
+     * "dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags=" of a 
connection string is accepted too). Note the
+     * empty tag set at the end, which means match any secondary as a last 
resort. Order matters when using multiple tag
+     * sets. The tag sets need a readPreference other than PRIMARY.
      */
     public void setReadPreferenceTags(String readPreferenceTags) {
         this.readPreferenceTags = readPreferenceTags;
diff --git 
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbEndpointClientOptionsTest.java
 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbEndpointClientOptionsTest.java
new file mode 100644
index 000000000000..bbb38251ff94
--- /dev/null
+++ 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbEndpointClientOptionsTest.java
@@ -0,0 +1,281 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.mongodb;
+
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import com.mongodb.MongoClientSettings;
+import com.mongodb.MongoCompressor;
+import com.mongodb.ReadPreference;
+import com.mongodb.Tag;
+import com.mongodb.TagSet;
+import com.mongodb.TaggableReadPreference;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
+import com.mongodb.client.internal.MongoClientImpl;
+import com.mongodb.connection.ClusterConnectionMode;
+import com.mongodb.connection.ClusterSettings;
+import com.mongodb.connection.ConnectionPoolSettings;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * The client options of a mongodb endpoint (readPreference, replicaSet, the 
timeouts, the pool sizes and so on) are
+ * applied to the client it creates from hosts or connectionUriString, on top 
of the connection string.
+ */
+class MongoDbEndpointClientOptionsTest extends CamelTestSupport {
+
+    private static final String HOSTS = 
"mongodb:dummy?hosts=localhost:27017&database=test&collection=test&operation=findAll";
+    private static final String CONNECTION_URI_STRING_OPTIONS
+            = 
"mongodb:dummy?connectionUriString=RAW(mongodb://localhost:27017/?readPreference=nearest&maxPoolSize=7"
+              + "&appName=fromUri&compressors=zlib,snappy&retryWrites=false)"
+              + "&database=test&collection=test&operation=findAll";
+
+    private MongoDbEndpoint endpoint(String uri) {
+        return context.getEndpoint(uri, MongoDbEndpoint.class);
+    }
+
+    private MongoClientSettings settings(String uri) {
+        return endpoint(uri).createMongoClientSettings();
+    }
+
+    @Test
+    void defaultsAreTheDriverDefaults() {
+        MongoDbEndpoint endpoint = endpoint(HOSTS);
+        MongoClientSettings settings = endpoint.createMongoClientSettings();
+        MongoClientSettings driver = MongoClientSettings.builder().build();
+
+        assertThat(endpoint.getClientOptionsSet()).isEmpty();
+        
assertThat(settings.getReadPreference()).isEqualTo(ReadPreference.primary());
+        
assertThat(settings.getConnectionPoolSettings()).isEqualTo(driver.getConnectionPoolSettings());
+        
assertThat(settings.getSocketSettings()).isEqualTo(driver.getSocketSettings());
+        
assertThat(settings.getServerSettings()).isEqualTo(driver.getServerSettings());
+        
assertThat(settings.getClusterSettings().getServerSelectionTimeout(TimeUnit.MILLISECONDS)).isEqualTo(30000);
+        
assertThat(settings.getClusterSettings().getLocalThreshold(TimeUnit.MILLISECONDS)).isEqualTo(15);
+        
assertThat(settings.getClusterSettings().getMode()).isEqualTo(ClusterConnectionMode.SINGLE);
+        assertThat(settings.getApplicationName()).isNull();
+        assertThat(settings.getCompressorList()).isEmpty();
+        assertThat(settings.getRetryWrites()).isTrue();
+        assertThat(settings.getRetryReads()).isTrue();
+    }
+
+    @Test
+    void readPreferenceIsApplied() {
+        assertThat(settings(HOSTS + 
"&readPreference=SECONDARY").getReadPreference()).isEqualTo(ReadPreference.secondary());
+    }
+
+    @Test
+    void readPreferenceWithUnderscoreIsApplied() {
+        assertThat(settings(HOSTS + 
"&readPreference=SECONDARY_PREFERRED").getReadPreference())
+                .isEqualTo(ReadPreference.secondaryPreferred());
+        assertThat(settings(HOSTS + 
"&readPreference=PRIMARY_PREFERRED").getReadPreference())
+                .isEqualTo(ReadPreference.primaryPreferred());
+        assertThat(settings(HOSTS + 
"&readPreference=secondaryPreferred").getReadPreference())
+                .isEqualTo(ReadPreference.secondaryPreferred());
+    }
+
+    @Test
+    void readPreferenceTagsAndMaxStalenessAreApplied() {
+        ReadPreference readPreference = settings(
+                HOSTS + 
"&readPreference=SECONDARY&readPreferenceTags=dc:ny,rack:1;dc:ny;&maxStalenessSeconds=120")
+                .getReadPreference();
+
+        TaggableReadPreference taggable = (TaggableReadPreference) 
readPreference;
+        assertThat(taggable.getName()).isEqualTo("secondary");
+        assertThat(taggable.getTagSetList()).containsExactly(
+                new TagSet(List.of(new Tag("dc", "ny"), new Tag("rack", "1"))),
+                new TagSet(new Tag("dc", "ny")),
+                new TagSet());
+        assertThat(taggable.getMaxStaleness(TimeUnit.SECONDS)).isEqualTo(120);
+    }
+
+    @Test
+    void readPreferenceTagsInConnectionStringForm() {
+        
assertThat(MongoDbEndpoint.parseReadPreferenceTags("dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags="))
+                .containsExactly(
+                        new TagSet(List.of(new Tag("dc", "ny"), new 
Tag("rack", "1"))),
+                        new TagSet(new Tag("dc", "ny")),
+                        new TagSet());
+        assertThat(MongoDbEndpoint.parseReadPreferenceTags(" dc : ny 
")).containsExactly(new TagSet(new Tag("dc", "ny")));
+    }
+
+    @Test
+    void invalidReadPreferenceTagFails() {
+        assertThatThrownBy(() -> MongoDbEndpoint.parseReadPreferenceTags("dc"))
+                .isInstanceOf(IllegalArgumentException.class)
+                .hasMessageContaining("key:value");
+    }
+
+    @Test
+    void readPreferenceTagsWithPrimaryFails() {
+        // the endpoint creates its client when it starts, so it fails to start
+        assertThatThrownBy(() -> endpoint(HOSTS + "&readPreferenceTags=dc:ny"))
+                .hasRootCauseInstanceOf(IllegalArgumentException.class)
+                .hasMessageContaining("Primary read preference can not also 
specify tag sets");
+    }
+
+    @Test
+    void readPreferenceOfConnectionUriStringIsKept() {
+        
assertThat(settings(CONNECTION_URI_STRING_OPTIONS).getReadPreference()).isEqualTo(ReadPreference.nearest());
+    }
+
+    @Test
+    void readPreferenceOfEndpointOverridesConnectionUriString() {
+        assertThat(settings(CONNECTION_URI_STRING_OPTIONS + 
"&readPreference=SECONDARY").getReadPreference())
+                .isEqualTo(ReadPreference.secondary());
+    }
+
+    @Test
+    void optionsOfConnectionUriStringAreKept() {
+        MongoClientSettings settings = settings(CONNECTION_URI_STRING_OPTIONS);
+
+        
assertThat(settings.getConnectionPoolSettings().getMaxSize()).isEqualTo(7);
+        assertThat(settings.getApplicationName()).isEqualTo("fromUri");
+        
assertThat(settings.getCompressorList()).extracting(MongoCompressor::getName).containsExactly("zlib",
 "snappy");
+        assertThat(settings.getRetryWrites()).isFalse();
+    }
+
+    @Test
+    void optionsOfEndpointOverrideConnectionUriString() {
+        MongoClientSettings settings = settings(
+                CONNECTION_URI_STRING_OPTIONS + 
"&maxPoolSize=20&appName=fromEndpoint&compressors=zstd");
+
+        
assertThat(settings.getConnectionPoolSettings().getMaxSize()).isEqualTo(20);
+        assertThat(settings.getApplicationName()).isEqualTo("fromEndpoint");
+        
assertThat(settings.getCompressorList()).extracting(MongoCompressor::getName).containsExactly("zstd");
+    }
+
+    @Test
+    void timeoutAndPoolOptionsAreApplied() {
+        MongoClientSettings settings = settings(HOSTS + 
"&serverSelectionTimeoutMS=1500&localThresholdMS=30"
+                                                + 
"&heartbeatFrequencyMS=2500&connectTimeoutMS=3000&socketTimeoutMS=4000"
+                                                + 
"&maxIdleTimeMS=5000&maxLifeTimeMS=6000&minPoolSize=3&maxPoolSize=9"
+                                                + 
"&maxConnecting=4&waitQueueTimeoutMS=7000");
+
+        ClusterSettings cluster = settings.getClusterSettings();
+        
assertThat(cluster.getServerSelectionTimeout(TimeUnit.MILLISECONDS)).isEqualTo(1500);
+        
assertThat(cluster.getLocalThreshold(TimeUnit.MILLISECONDS)).isEqualTo(30);
+        
assertThat(settings.getServerSettings().getHeartbeatFrequency(TimeUnit.MILLISECONDS)).isEqualTo(2500);
+        
assertThat(settings.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)).isEqualTo(3000);
+        
assertThat(settings.getSocketSettings().getReadTimeout(TimeUnit.MILLISECONDS)).isEqualTo(4000);
+        ConnectionPoolSettings pool = settings.getConnectionPoolSettings();
+        
assertThat(pool.getMaxConnectionIdleTime(TimeUnit.MILLISECONDS)).isEqualTo(5000);
+        
assertThat(pool.getMaxConnectionLifeTime(TimeUnit.MILLISECONDS)).isEqualTo(6000);
+        assertThat(pool.getMinSize()).isEqualTo(3);
+        assertThat(pool.getMaxSize()).isEqualTo(9);
+        assertThat(pool.getMaxConnecting()).isEqualTo(4);
+        assertThat(pool.getMaxWaitTime(TimeUnit.MILLISECONDS)).isEqualTo(7000);
+    }
+
+    @Test
+    void replicaSetDiscoversTheMembers() {
+        ClusterSettings cluster = settings(HOSTS + 
"&replicaSet=rs0").getClusterSettings();
+
+        assertThat(cluster.getRequiredReplicaSetName()).isEqualTo("rs0");
+        
assertThat(cluster.getMode()).isEqualTo(ClusterConnectionMode.MULTIPLE);
+    }
+
+    @Test
+    void directConnectionUsesTheHostOnly() {
+        ClusterSettings cluster = settings(HOSTS + 
"&replicaSet=rs0&directConnection=true").getClusterSettings();
+
+        assertThat(cluster.getMode()).isEqualTo(ClusterConnectionMode.SINGLE);
+    }
+
+    @Test
+    void loadBalancedIsApplied() {
+        assertThat(settings(HOSTS + 
"&loadBalanced=true").getClusterSettings().getMode())
+                .isEqualTo(ClusterConnectionMode.LOAD_BALANCED);
+    }
+
+    @Test
+    void srvOptionsAreApplied() {
+        ClusterSettings cluster = settings(
+                
"mongodb:dummy?connectionUriString=RAW(mongodb+srv://cluster.example.com/)"
+                                           + 
"&srvServiceName=custom&srvMaxHosts=2&database=test&collection=test&operation=findAll")
+                .getClusterSettings();
+
+        assertThat(cluster.getSrvServiceName()).isEqualTo("custom");
+        assertThat(cluster.getSrvMaxHosts()).isEqualTo(2);
+    }
+
+    @Test
+    void compressorsAreApplied() {
+        MongoClientSettings settings = settings(HOSTS + 
"&compressors=zlib,snappy,zstd&zlibCompressionLevel=6");
+
+        
assertThat(settings.getCompressorList()).extracting(MongoCompressor::getName).containsExactly("zlib",
 "snappy",
+                "zstd");
+        Integer level = 
settings.getCompressorList().get(0).getProperty(MongoCompressor.LEVEL, null);
+        assertThat(level).isEqualTo(6);
+    }
+
+    @Test
+    void zlibCompressionLevelAppliesToZlibOfConnectionUriString() {
+        MongoClientSettings settings = settings(CONNECTION_URI_STRING_OPTIONS 
+ "&zlibCompressionLevel=3");
+
+        
assertThat(settings.getCompressorList()).extracting(MongoCompressor::getName).containsExactly("zlib",
 "snappy");
+        Integer level = 
settings.getCompressorList().get(0).getProperty(MongoCompressor.LEVEL, null);
+        assertThat(level).isEqualTo(3);
+    }
+
+    @Test
+    void unknownCompressorFails() {
+        assertThatThrownBy(() -> endpoint(HOSTS + "&compressors=lz4"))
+                .hasRootCauseInstanceOf(IllegalArgumentException.class)
+                .hasMessageContaining("Unsupported compressor lz4");
+    }
+
+    @Test
+    void appNameAndRetriesAreApplied() {
+        MongoClientSettings settings = settings(HOSTS + 
"&appName=myApp&retryWrites=false&retryReads=false");
+
+        assertThat(settings.getApplicationName()).isEqualTo("myApp");
+        assertThat(settings.getRetryWrites()).isFalse();
+        assertThat(settings.getRetryReads()).isFalse();
+    }
+
+    @Test
+    void clientCreatedFromHostsUsesTheOptions() throws Exception {
+        MongoDbEndpoint endpoint = endpoint(HOSTS + 
"&readPreference=SECONDARY&maxPoolSize=5");
+        endpoint.initializeConnection();
+
+        MongoClientSettings settings
+                = ((MongoClientImpl) 
endpoint.getMongoConnection()).getSettings();
+        
assertThat(settings.getReadPreference()).isEqualTo(ReadPreference.secondary());
+        
assertThat(settings.getConnectionPoolSettings().getMaxSize()).isEqualTo(5);
+        // the tailable consumer and the producer read with the read 
preference of the collection
+        
assertThat(endpoint.getMongoCollection().getReadPreference()).isEqualTo(ReadPreference.secondary());
+    }
+
+    @Test
+    void optionsAreReportedForAClientFromTheRegistry() {
+        try (MongoClient client = 
MongoClients.create("mongodb://localhost:27017")) {
+            context.getRegistry().bind("myDb", client);
+
+            MongoDbEndpoint endpoint = endpoint(
+                    
"mongodb:myDb?database=test&collection=test&operation=findAll&readPreference=SECONDARY&maxPoolSize=5");
+
+            // the client is not created by the endpoint, so the options 
cannot be applied to it
+            assertThat(endpoint.getMongoConnection()).isSameAs(client);
+            
assertThat(endpoint.getClientOptionsSet()).containsExactly("maxPoolSize", 
"readPreference");
+        }
+    }
+}
diff --git 
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/integration/MongoDbClientOptionsIT.java
 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/integration/MongoDbClientOptionsIT.java
new file mode 100644
index 000000000000..400e61cf521c
--- /dev/null
+++ 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/integration/MongoDbClientOptionsIT.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.mongodb.integration;
+
+import java.util.List;
+
+import com.mongodb.ReadPreference;
+import org.apache.camel.CamelContext;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mongodb.MongoDbEndpoint;
+import org.apache.camel.test.infra.core.annotations.RouteFixture;
+import org.apache.camel.test.infra.core.api.ConfigurableRoute;
+import org.bson.Document;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * The client options of an endpoint with hosts reach the MongoDB server.
+ */
+// public: the RouteFixture of the test-infra is called by reflection
+public class MongoDbClientOptionsIT extends AbstractMongoDbITSupport 
implements ConfigurableRoute {
+
+    private static final String APP_NAME = "camel-27193-it";
+
+    private String currentOpUri() {
+        return "mongodb:dummy?hosts=" + service.getConnectionAddress() + 
"&database=admin&operation=command&appName="
+               + APP_NAME;
+    }
+
+    @Test
+    void appNameIsSentToTheServer() {
+        // the operations of the clients with this application name, which 
includes this currentOp command itself
+        Document result = template.requestBody("direct:currentOp",
+                "{\"currentOp\": true, \"$all\": true, \"appName\": \"" + 
APP_NAME + "\"}", Document.class);
+
+        List<Document> inprog = result.getList("inprog", Document.class);
+        assertThat(inprog).isNotEmpty().allSatisfy(op -> 
assertThat(op.getString("appName")).isEqualTo(APP_NAME));
+    }
+
+    @Test
+    void readPreferenceIsUsedByTheCollection() {
+        MongoDbEndpoint endpoint = context.getEndpoint(
+                "mongodb:dummy?hosts=" + service.getConnectionAddress()
+                                                       + 
"&database={{mongodb.testDb}}&collection={{mongodb.testCollection}}"
+                                                       + 
"&operation=count&readPreference=SECONDARY_PREFERRED",
+                MongoDbEndpoint.class);
+
+        Long count = template.requestBody(endpoint, "{}", Long.class);
+
+        assertThat(count).isZero();
+        
assertThat(endpoint.getMongoCollection().getReadPreference()).isEqualTo(ReadPreference.secondaryPreferred());
+    }
+
+    @RouteFixture
+    @Override
+    public void createRouteBuilder(CamelContext context) throws Exception {
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:currentOp").to(currentOpUri());
+            }
+        });
+    }
+}
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index aefced92c578..db7cc87bdb57 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -7474,6 +7474,29 @@ server must accept TLS connections, and its certificate 
must be trusted by the J
 When none of these options is set, the TLS settings of `connectionUriString` 
(for example `?tls=true`) are used as
 before.
 
+=== camel-mongodb - readPreference and the other client options are applied
+
+The client options of the `mongodb` endpoint were not used: `replicaSet`, 
`readPreference`, `readPreferenceTags`,
+`maxStalenessSeconds`, `appName`, `compressors`, `zlibCompressionLevel`, 
`connectTimeoutMS`, `socketTimeoutMS`,
+`serverSelectionTimeoutMS`, `localThresholdMS`, `heartbeatFrequencyMS`, 
`maxIdleTimeMS`, `maxLifeTimeMS`,
+`minPoolSize`, `maxPoolSize`, `maxConnecting`, `waitQueueTimeoutMS`, 
`srvServiceName`, `srvMaxHosts`, `retryWrites`,
+`retryReads`, `directConnection` and `loadBalanced`. They are now applied to 
the client the endpoint creates from `hosts`
+or `connectionUriString`. An endpoint that set one of them now gets that 
behaviour: for example, with
+`readPreference=SECONDARY` it reads from a secondary (and fails to read when 
the replica set has none), and with
+`replicaSet` and a single host in `hosts` the driver discovers the other 
members of the replica set.
+
+An option is applied only when its value differs from its default, and then it 
overrides the same option in
+`connectionUriString`. An option left at its default keeps the value of the 
connection string, as before.
+
+As the options are now read, an invalid value (for example an unknown 
`readPreference` or `compressors` value, or
+`readPreferenceTags` with the `PRIMARY` read preference) makes the endpoint 
fail to start. The documented
+`readPreference` values `PRIMARY_PREFERRED` and `SECONDARY_PREFERRED` are 
accepted, as are the driver names
+`primaryPreferred` and `secondaryPreferred`.
+
+The options cannot change a `MongoClient` the endpoint did not create (set 
with `mongoConnection`, on the component, or
+from the registry). Such an endpoint now logs a WARN that lists the options it 
does not use; configure them on the
+`MongoClient` instead.
+
 === camel-mongodb-gridfs - the consumer routes a file once, offers the file of 
a failed exchange again and sets CamelFileName, and an unknown operation fails
 
 With the `TimeStamp` (default) and `PersistentTimestamp` query strategies, the 
`mongodb-gridfs` consumer routed
diff --git 
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MongoDbEndpointBuilderFactory.java
 
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MongoDbEndpointBuilderFactory.java
index 71b23f1d745b..a2a719d26e72 100644
--- 
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MongoDbEndpointBuilderFactory.java
+++ 
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MongoDbEndpointBuilderFactory.java
@@ -1279,8 +1279,13 @@ public interface MongoDbEndpointBuilderFactory {
          * A representation of a tag set as a comma-separated list of
          * colon-separated key-value pairs, e.g. dc:ny,rack:1. Spaces are
          * stripped from the beginning and end of all keys and values. To
-         * specify a list of tag sets, using multiple readPreferenceTags, e.g.,
-         * 
readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags= 
Note the empty value for the last one, which means match any secondary as a 
last resort. Order matters when using multiple readPreferenceTags.
+         * specify a list of tag sets, separate them with semicolons, e.g.
+         * dc:ny,rack:1;dc:ny; (the form
+         * dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags= of a
+         * connection string is accepted too). Note the empty tag set at the
+         * end, which means match any secondary as a last resort. Order matters
+         * when using multiple tag sets. The tag sets need a readPreference
+         * other than PRIMARY.
          * 
          * The option is a: <code>java.lang.String</code> type.
          * 
@@ -2559,8 +2564,13 @@ public interface MongoDbEndpointBuilderFactory {
          * A representation of a tag set as a comma-separated list of
          * colon-separated key-value pairs, e.g. dc:ny,rack:1. Spaces are
          * stripped from the beginning and end of all keys and values. To
-         * specify a list of tag sets, using multiple readPreferenceTags, e.g.,
-         * 
readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags= 
Note the empty value for the last one, which means match any secondary as a 
last resort. Order matters when using multiple readPreferenceTags.
+         * specify a list of tag sets, separate them with semicolons, e.g.
+         * dc:ny,rack:1;dc:ny; (the form
+         * dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags= of a
+         * connection string is accepted too). Note the empty tag set at the
+         * end, which means match any secondary as a last resort. Order matters
+         * when using multiple tag sets. The tag sets need a readPreference
+         * other than PRIMARY.
          * 
          * The option is a: <code>java.lang.String</code> type.
          * 
@@ -3797,8 +3807,13 @@ public interface MongoDbEndpointBuilderFactory {
          * A representation of a tag set as a comma-separated list of
          * colon-separated key-value pairs, e.g. dc:ny,rack:1. Spaces are
          * stripped from the beginning and end of all keys and values. To
-         * specify a list of tag sets, using multiple readPreferenceTags, e.g.,
-         * 
readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags= 
Note the empty value for the last one, which means match any secondary as a 
last resort. Order matters when using multiple readPreferenceTags.
+         * specify a list of tag sets, separate them with semicolons, e.g.
+         * dc:ny,rack:1;dc:ny; (the form
+         * dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags= of a
+         * connection string is accepted too). Note the empty tag set at the
+         * end, which means match any secondary as a last resort. Order matters
+         * when using multiple tag sets. The tag sets need a readPreference
+         * other than PRIMARY.
          * 
          * The option is a: <code>java.lang.String</code> type.
          * 

Reply via email to