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

Croway pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new ee69fccd13c3 CAMEL-27056: camel-mongodb - an endpoint with 
connectionUriString creates its client from it, also without hosts, and closes 
the client it created when it stops (#30226)
ee69fccd13c3 is described below

commit ee69fccd13c36aa7513e56887b84ba8ef6fc569b
Author: Federico Mariani <[email protected]>
AuthorDate: Tue Nov 17 17:00:39 2026 +0100

    CAMEL-27056: camel-mongodb - an endpoint with connectionUriString creates 
its client from it, also without hosts, and closes the client it created when 
it stops (#30226)
    
    * CAMEL-27056: camel-mongodb - an endpoint with connectionUriString creates 
its client from it, also without hosts
    
    * CAMEL-27056: camel-mongodb - the endpoint closes the client it created 
when it stops
    
    * CAMEL-27056: camel-mongodb - the lifecycle test makes the registry bean 
endpoint use the bean, and checks each endpoint's client
---
 .../apache/camel/catalog/components/mongodb.json   |   6 +-
 .../camel/catalog/docs/mongodb-component.adoc      |  13 ++
 .../apache/camel/component/mongodb/mongodb.json    |   6 +-
 .../src/main/docs/mongodb-component.adoc           |  13 ++
 .../camel/component/mongodb/MongoDbComponent.java  |   3 +-
 .../camel/component/mongodb/MongoDbEndpoint.java   |  37 ++++-
 .../MongoDbEndpointClientLifecycleTest.java        | 159 +++++++++++++++++++++
 .../MongoDbEndpointConnectionUriStringTest.java    |  96 +++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |  17 +++
 .../dsl/MongodbComponentBuilderFactory.java        |   3 +-
 .../builder/endpoint/StaticEndpointBuilders.java   |   6 +-
 .../dsl/MongoDbEndpointBuilderFactory.java         |  18 ++-
 12 files changed, 359 insertions(+), 18 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 d25475fb600d..117f654e930b 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
@@ -24,7 +24,7 @@
     "remote": true
   },
   "componentProperties": {
-    "mongoConnection": { "index": 0, "kind": "property", "displayName": "Mongo 
Connection", "group": "common", "label": "", "required": false, "type": 
"object", "javaType": "com.mongodb.client.MongoClient", "deprecated": false, 
"autowired": true, "secret": false, "description": "Shared client used for 
connection. All endpoints generated from the component will share this 
connection client." },
+    "mongoConnection": { "index": 0, "kind": "property", "displayName": "Mongo 
Connection", "group": "common", "label": "", "required": false, "type": 
"object", "javaType": "com.mongodb.client.MongoClient", "deprecated": false, 
"autowired": true, "secret": false, "description": "Shared client used for 
connection. All endpoints generated from the component will share this 
connection client, except the endpoints that set hosts or connectionUriString, 
which create their own client." },
     "bridgeErrorHandler": { "index": 1, "kind": "property", "displayName": 
"Bridge Error Handler", "group": "consumer", "label": "consumer", "required": 
false, "type": "boolean", "javaType": "boolean", "deprecated": false, 
"autowired": false, "secret": false, "defaultValue": false, "description": 
"Allows for bridging the consumer to the Camel routing Error Handler, which 
mean any exceptions (if possible) occurred while the Camel consumer is trying 
to pickup incoming messages, or the like [...]
     "lazyStartProducer": { "index": 2, "kind": "property", "displayName": 
"Lazy Start Producer", "group": "producer", "label": "producer", "required": 
false, "type": "boolean", "javaType": "boolean", "deprecated": false, 
"autowired": false, "secret": false, "defaultValue": false, "description": 
"Whether the producer should be started lazy (on the first message). By 
starting lazy you can use this to allow CamelContext and routes to startup in 
situations where a producer may otherwise fail [...]
     "autowiredEnabled": { "index": 3, "kind": "property", "displayName": 
"Autowired Enabled", "group": "advanced", "label": "advanced", "required": 
false, "type": "boolean", "javaType": "boolean", "deprecated": false, 
"autowired": false, "secret": false, "defaultValue": true, "description": 
"Whether autowiring is enabled. This is used for automatic autowiring options 
(the option must be marked as autowired) by looking up in the registry to find 
if there is a single instance of matching t [...]
@@ -64,10 +64,10 @@
     "producerOut": { "carriers": [ "unknown" ], "dependsOn": [ "outputType", 
"writeResultAsHeader" ], "byOption": [ { "option": "operation", "value": 
"findById", "carriers": [ "pojo", "null" ], "javaType": "org.bson.Document" }, 
{ "option": "operation", "value": "findOneByQuery", "carriers": [ "pojo", 
"null" ], "javaType": "org.bson.Document" }, { "option": "operation", "value": 
"findOneAndDelete", "carriers": [ "pojo", "null" ], "javaType": 
"org.bson.Document" }, { "option": "operation" [...]
   },
   "properties": {
-    "connectionBean": { "index": 0, "kind": "path", "displayName": "Connection 
Bean", "group": "common", "label": "", "required": true, "type": "string", 
"javaType": "java.lang.String", "deprecated": false, "autowired": false, 
"secret": false, "description": "Sets the connection bean reference used to 
lookup a client for connecting to a database if no hosts parameter is present." 
},
+    "connectionBean": { "index": 0, "kind": "path", "displayName": "Connection 
Bean", "group": "common", "label": "", "required": true, "type": "string", 
"javaType": "java.lang.String", "deprecated": false, "autowired": false, 
"secret": false, "description": "Sets the connection bean reference used to 
lookup a client for connecting to a database if neither the hosts nor the 
connectionUriString parameter is present." },
     "collection": { "index": 1, "kind": "parameter", "displayName": 
"Collection", "group": "common", "label": "", "required": false, "type": 
"string", "javaType": "java.lang.String", "deprecated": false, "autowired": 
false, "secret": false, "endpointIdentity": true, "description": "Sets the name 
of the MongoDB collection to bind to this endpoint" },
     "collectionIndex": { "index": 2, "kind": "parameter", "displayName": 
"Collection Index", "group": "common", "label": "", "required": false, "type": 
"string", "javaType": "java.lang.String", "deprecated": false, "autowired": 
false, "secret": false, "description": "Sets the collection index (JSON FORMAT 
: { field1 : order1, field2 : order2})" },
-    "connectionUriString": { "index": 3, "kind": "parameter", "displayName": 
"Connection Uri String", "group": "common", "label": "common", "required": 
false, "type": "string", "javaType": "java.lang.String", "deprecated": false, 
"autowired": false, "secret": false, "description": "Set the whole Connection 
String\/Uri for mongodb endpoint." },
+    "connectionUriString": { "index": 3, "kind": "parameter", "displayName": 
"Connection Uri String", "group": "common", "label": "common", "required": 
false, "type": "string", "javaType": "java.lang.String", "deprecated": false, 
"autowired": false, "secret": false, "description": "Set the whole Connection 
String\/Uri for mongodb endpoint. When set, the endpoint creates its client 
from it, instead of using the client of the component or the connectionBean." },
     "createCollection": { "index": 4, "kind": "parameter", "displayName": 
"Create Collection", "group": "common", "label": "", "required": false, "type": 
"boolean", "javaType": "boolean", "deprecated": false, "autowired": false, 
"secret": false, "defaultValue": true, "description": "Create the collection 
during initialisation if it doesn't exist. Default is true." },
     "database": { "index": 5, "kind": "parameter", "displayName": "Database", 
"group": "common", "label": "", "required": false, "type": "string", 
"javaType": "java.lang.String", "deprecated": false, "autowired": false, 
"secret": false, "endpointIdentity": true, "description": "Sets the name of the 
MongoDB database to target" },
     "hosts": { "index": 6, "kind": "parameter", "displayName": "Hosts", 
"group": "common", "label": "", "required": false, "type": "string", 
"javaType": "java.lang.String", "deprecated": false, "autowired": false, 
"secret": false, "description": "Host address of mongodb server in 
[host]:[port] format. It's possible to also use more than one address, as a 
comma separated list of hosts: [host1]:[port1],[host2]:[port2]. If this 
parameter is specified, the provided connectionBean is ignored." },
diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
index 55f9b0d837cf..b8df7924241d 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
@@ -60,8 +60,21 @@ for this component:
 ----
 
mongodb:connectionBean?database=databaseName&collection=collectionName&operation=operationName[&moreOptions...]
 
mongodb:dummy?hosts=hostnames&database=databaseName&collection=collectionName&operation=operationName[&moreOptions...]
+mongodb:dummy?connectionUriString=RAW(mongodb://host:port)&database=databaseName&collection=collectionName&operation=operationName[&moreOptions...]
 ----
 
+The endpoint uses the first client it finds in this order:
+
+. the client set with the `mongoConnection` endpoint option
+. a client the endpoint creates from the `connectionUriString` or `hosts` 
option
+. the `mongoConnection` client of the component, which is autowired when the 
registry holds exactly one `MongoClient`
+. the `MongoClient` bean named by the endpoint path (`connectionBean`)
+
+A client the endpoint creates from `connectionUriString` or `hosts` belongs to 
that endpoint: each such endpoint has its
+own client and connection pool, and closes it when it stops (for example when 
its route is removed or reloaded, or when
+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`.
+
 // component options: START
 include::partial$component-configure-options.adoc[]
 include::partial$component-endpoint-options.adoc[]
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 d25475fb600d..117f654e930b 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
@@ -24,7 +24,7 @@
     "remote": true
   },
   "componentProperties": {
-    "mongoConnection": { "index": 0, "kind": "property", "displayName": "Mongo 
Connection", "group": "common", "label": "", "required": false, "type": 
"object", "javaType": "com.mongodb.client.MongoClient", "deprecated": false, 
"autowired": true, "secret": false, "description": "Shared client used for 
connection. All endpoints generated from the component will share this 
connection client." },
+    "mongoConnection": { "index": 0, "kind": "property", "displayName": "Mongo 
Connection", "group": "common", "label": "", "required": false, "type": 
"object", "javaType": "com.mongodb.client.MongoClient", "deprecated": false, 
"autowired": true, "secret": false, "description": "Shared client used for 
connection. All endpoints generated from the component will share this 
connection client, except the endpoints that set hosts or connectionUriString, 
which create their own client." },
     "bridgeErrorHandler": { "index": 1, "kind": "property", "displayName": 
"Bridge Error Handler", "group": "consumer", "label": "consumer", "required": 
false, "type": "boolean", "javaType": "boolean", "deprecated": false, 
"autowired": false, "secret": false, "defaultValue": false, "description": 
"Allows for bridging the consumer to the Camel routing Error Handler, which 
mean any exceptions (if possible) occurred while the Camel consumer is trying 
to pickup incoming messages, or the like [...]
     "lazyStartProducer": { "index": 2, "kind": "property", "displayName": 
"Lazy Start Producer", "group": "producer", "label": "producer", "required": 
false, "type": "boolean", "javaType": "boolean", "deprecated": false, 
"autowired": false, "secret": false, "defaultValue": false, "description": 
"Whether the producer should be started lazy (on the first message). By 
starting lazy you can use this to allow CamelContext and routes to startup in 
situations where a producer may otherwise fail [...]
     "autowiredEnabled": { "index": 3, "kind": "property", "displayName": 
"Autowired Enabled", "group": "advanced", "label": "advanced", "required": 
false, "type": "boolean", "javaType": "boolean", "deprecated": false, 
"autowired": false, "secret": false, "defaultValue": true, "description": 
"Whether autowiring is enabled. This is used for automatic autowiring options 
(the option must be marked as autowired) by looking up in the registry to find 
if there is a single instance of matching t [...]
@@ -64,10 +64,10 @@
     "producerOut": { "carriers": [ "unknown" ], "dependsOn": [ "outputType", 
"writeResultAsHeader" ], "byOption": [ { "option": "operation", "value": 
"findById", "carriers": [ "pojo", "null" ], "javaType": "org.bson.Document" }, 
{ "option": "operation", "value": "findOneByQuery", "carriers": [ "pojo", 
"null" ], "javaType": "org.bson.Document" }, { "option": "operation", "value": 
"findOneAndDelete", "carriers": [ "pojo", "null" ], "javaType": 
"org.bson.Document" }, { "option": "operation" [...]
   },
   "properties": {
-    "connectionBean": { "index": 0, "kind": "path", "displayName": "Connection 
Bean", "group": "common", "label": "", "required": true, "type": "string", 
"javaType": "java.lang.String", "deprecated": false, "autowired": false, 
"secret": false, "description": "Sets the connection bean reference used to 
lookup a client for connecting to a database if no hosts parameter is present." 
},
+    "connectionBean": { "index": 0, "kind": "path", "displayName": "Connection 
Bean", "group": "common", "label": "", "required": true, "type": "string", 
"javaType": "java.lang.String", "deprecated": false, "autowired": false, 
"secret": false, "description": "Sets the connection bean reference used to 
lookup a client for connecting to a database if neither the hosts nor the 
connectionUriString parameter is present." },
     "collection": { "index": 1, "kind": "parameter", "displayName": 
"Collection", "group": "common", "label": "", "required": false, "type": 
"string", "javaType": "java.lang.String", "deprecated": false, "autowired": 
false, "secret": false, "endpointIdentity": true, "description": "Sets the name 
of the MongoDB collection to bind to this endpoint" },
     "collectionIndex": { "index": 2, "kind": "parameter", "displayName": 
"Collection Index", "group": "common", "label": "", "required": false, "type": 
"string", "javaType": "java.lang.String", "deprecated": false, "autowired": 
false, "secret": false, "description": "Sets the collection index (JSON FORMAT 
: { field1 : order1, field2 : order2})" },
-    "connectionUriString": { "index": 3, "kind": "parameter", "displayName": 
"Connection Uri String", "group": "common", "label": "common", "required": 
false, "type": "string", "javaType": "java.lang.String", "deprecated": false, 
"autowired": false, "secret": false, "description": "Set the whole Connection 
String\/Uri for mongodb endpoint." },
+    "connectionUriString": { "index": 3, "kind": "parameter", "displayName": 
"Connection Uri String", "group": "common", "label": "common", "required": 
false, "type": "string", "javaType": "java.lang.String", "deprecated": false, 
"autowired": false, "secret": false, "description": "Set the whole Connection 
String\/Uri for mongodb endpoint. When set, the endpoint creates its client 
from it, instead of using the client of the component or the connectionBean." },
     "createCollection": { "index": 4, "kind": "parameter", "displayName": 
"Create Collection", "group": "common", "label": "", "required": false, "type": 
"boolean", "javaType": "boolean", "deprecated": false, "autowired": false, 
"secret": false, "defaultValue": true, "description": "Create the collection 
during initialisation if it doesn't exist. Default is true." },
     "database": { "index": 5, "kind": "parameter", "displayName": "Database", 
"group": "common", "label": "", "required": false, "type": "string", 
"javaType": "java.lang.String", "deprecated": false, "autowired": false, 
"secret": false, "endpointIdentity": true, "description": "Sets the name of the 
MongoDB database to target" },
     "hosts": { "index": 6, "kind": "parameter", "displayName": "Hosts", 
"group": "common", "label": "", "required": false, "type": "string", 
"javaType": "java.lang.String", "deprecated": false, "autowired": false, 
"secret": false, "description": "Host address of mongodb server in 
[host]:[port] format. It's possible to also use more than one address, as a 
comma separated list of hosts: [host1]:[port1],[host2]:[port2]. If this 
parameter is specified, the provided connectionBean is ignored." },
diff --git a/components/camel-mongodb/src/main/docs/mongodb-component.adoc 
b/components/camel-mongodb/src/main/docs/mongodb-component.adoc
index 55f9b0d837cf..b8df7924241d 100644
--- a/components/camel-mongodb/src/main/docs/mongodb-component.adoc
+++ b/components/camel-mongodb/src/main/docs/mongodb-component.adoc
@@ -60,8 +60,21 @@ for this component:
 ----
 
mongodb:connectionBean?database=databaseName&collection=collectionName&operation=operationName[&moreOptions...]
 
mongodb:dummy?hosts=hostnames&database=databaseName&collection=collectionName&operation=operationName[&moreOptions...]
+mongodb:dummy?connectionUriString=RAW(mongodb://host:port)&database=databaseName&collection=collectionName&operation=operationName[&moreOptions...]
 ----
 
+The endpoint uses the first client it finds in this order:
+
+. the client set with the `mongoConnection` endpoint option
+. a client the endpoint creates from the `connectionUriString` or `hosts` 
option
+. the `mongoConnection` client of the component, which is autowired when the 
registry holds exactly one `MongoClient`
+. the `MongoClient` bean named by the endpoint path (`connectionBean`)
+
+A client the endpoint creates from `connectionUriString` or `hosts` belongs to 
that endpoint: each such endpoint has its
+own client and connection pool, and closes it when it stops (for example when 
its route is removed or reloaded, or when
+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`.
+
 // 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/MongoDbComponent.java
 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbComponent.java
index 0a6d1e92a382..c11c8efae7e3 100644
--- 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbComponent.java
+++ 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbComponent.java
@@ -72,7 +72,8 @@ public class MongoDbComponent extends DefaultComponent 
implements SSLContextPara
     }
 
     /**
-     * Shared client used for connection. All endpoints generated from the 
component will share this connection client.
+     * Shared client used for connection. All endpoints generated from the 
component will share this connection client,
+     * except the endpoints that set hosts or connectionUriString, which 
create their own client.
      */
     public void setMongoConnection(MongoClient mongoConnection) {
         this.mongoConnection = mongoConnection;
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 b3ed26ee61da..13e5f136ed08 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
@@ -130,7 +130,8 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
     @UriParam(description = "Sets the connection bean used as a client for 
connecting to a database.")
     private MongoClient mongoConnection;
 
-    @UriPath(description = "Sets the connection bean reference used to lookup 
a client for connecting to a database if no hosts parameter is present.")
+    @UriPath(description = "Sets the connection bean reference used to lookup 
a client for connecting to a database if"
+                           + " neither the hosts nor the connectionUriString 
parameter is present.")
     @Metadata(required = true)
     private String connectionBean;
 
@@ -255,7 +256,8 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
     private StateRepository<String, String> changeStreamTokenRepository;
     @UriParam(label = "consumer")
     private String changeStreamToken;
-    @UriParam(description = "Set the whole Connection String/Uri for mongodb 
endpoint.",
+    @UriParam(description = "Set the whole Connection String/Uri for mongodb 
endpoint. When set, the endpoint creates"
+                            + " its client from it, instead of using the 
client of the component or the connectionBean.",
               label = "common")
     private String connectionUriString;
 
@@ -266,6 +268,8 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
 
     private MongoDatabase mongoDatabase;
     private MongoCollection<Document> mongoCollection;
+    // the client this endpoint created from hosts or connectionUriString, 
which it closes when it stops
+    private volatile MongoClient createdMongoConnection;
 
     public MongoDbEndpoint() {
     }
@@ -493,15 +497,40 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
     protected void doStart() throws Exception {
         if (mongoConnection == null) {
             mongoConnection = resolveMongoConnection();
+            if (mongoDatabase != null) {
+                // started again after a stop closed the client the endpoint 
created: the producer and consumer use the
+                // database and collection of the new client
+                mongoDatabase = mongoConnection.getDatabase(database);
+                if (mongoCollection != null) {
+                    mongoCollection = mongoDatabase.getCollection(collection, 
Document.class);
+                }
+            }
         } else {
             LOG.debug("Resolved the connection provided by mongoConnection 
property parameter as {}", mongoConnection);
         }
         super.doStart();
     }
 
+    @Override
+    protected void doStop() throws Exception {
+        super.doStop();
+        // only the client this endpoint created is closed: a client set with 
mongoConnection, the client of the
+        // component or a bean from the registry may be shared with other 
endpoints
+        MongoClient created = createdMongoConnection;
+        if (created != null) {
+            createdMongoConnection = null;
+            if (mongoConnection == created) {
+                // a new client is created when the endpoint is started again
+                mongoConnection = null;
+            }
+            LOG.debug("Closing the MongoClient created by {}", this);
+            created.close();
+        }
+    }
+
     private MongoClient resolveMongoConnection() {
         MongoClient mongoClient;
-        if (this.hosts != null) {
+        if (this.hosts != null || this.connectionUriString != null) {
             String credentials = username == null ? "" : username;
             if (!credentials.isEmpty()) {
                 credentials += this.password == null ? "@" : ":" + password + 
"@";
@@ -516,6 +545,8 @@ public class MongoDbEndpoint extends DefaultEndpoint 
implements EndpointServiceL
             } else {
                 mongoClient = MongoClients.create(connectionUri);
             }
+            // doStart() and initializeConnection() both get their client 
here, so doStop() closes it whichever ran first
+            createdMongoConnection = mongoClient;
             LOG.debug("Connection created using provided credentials");
         } else {
             mongoClient = getComponent().getMongoConnection();
diff --git 
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbEndpointClientLifecycleTest.java
 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbEndpointClientLifecycleTest.java
new file mode 100644
index 000000000000..9161db2f8b2a
--- /dev/null
+++ 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbEndpointClientLifecycleTest.java
@@ -0,0 +1,159 @@
+/*
+ * 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 com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoDatabase;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+/**
+ * A mongodb endpoint closes the client it created from connectionUriString or 
hosts when it stops, and never closes a
+ * client it did not create.
+ */
+class MongoDbEndpointClientLifecycleTest extends CamelTestSupport {
+
+    private static final String URI_ENDPOINT
+            = 
"mongodb:dummy?connectionUriString=RAW(mongodb://localhost:27017)&database=test&collection=test&operation=findAll";
+    private static final String HOSTS_ENDPOINT
+            = 
"mongodb:dummy?hosts=localhost:27017&database=test&collection=test&operation=findAll";
+
+    @Test
+    void clientCreatedFromConnectionUriStringIsClosedWhenTheRouteIsRemoved() 
throws Exception {
+        assertClientClosedWhenTheRouteIsRemoved(URI_ENDPOINT);
+    }
+
+    @Test
+    void clientCreatedFromHostsIsClosedWhenTheRouteIsRemoved() throws 
Exception {
+        assertClientClosedWhenTheRouteIsRemoved(HOSTS_ENDPOINT);
+    }
+
+    @Test
+    void routeAddedAgainWithTheSameIdClosesTheClientOfTheReplacedRoute() 
throws Exception {
+        addRoute("mongo", URI_ENDPOINT);
+        MongoDbEndpoint first = context.getEndpoint(URI_ENDPOINT, 
MongoDbEndpoint.class);
+        MongoClient firstClient = first.getMongoConnection();
+
+        // as a route reload does: the route with the same id is stopped and 
removed, and the new one is added
+        addRoute("mongo", URI_ENDPOINT);
+
+        assertClosed(firstClient);
+        MongoClient secondClient = context.getEndpoint(URI_ENDPOINT, 
MongoDbEndpoint.class).getMongoConnection();
+        assertNotNull(secondClient);
+        assertNotSame(firstClient, secondClient);
+    }
+
+    @Test
+    void clientIsClosedWhenTheContextStops() throws Exception {
+        addRoute("mongo", URI_ENDPOINT);
+        MongoClient client = context.getEndpoint(URI_ENDPOINT, 
MongoDbEndpoint.class).getMongoConnection();
+
+        context.stop();
+
+        assertClosed(client);
+    }
+
+    @Test
+    void endpointStartedAgainCreatesANewClient() {
+        MongoDbEndpoint endpoint = context.getEndpoint(URI_ENDPOINT, 
MongoDbEndpoint.class);
+        endpoint.initializeConnection();
+        MongoClient firstClient = endpoint.getMongoConnection();
+        MongoDatabase firstDatabase = endpoint.getMongoDatabase();
+
+        endpoint.stop();
+        assertClosed(firstClient);
+
+        endpoint.start();
+        MongoClient secondClient = endpoint.getMongoConnection();
+        assertNotNull(secondClient);
+        assertNotSame(firstClient, secondClient);
+        // the database and collection the producer uses are taken from the 
new client
+        assertNotSame(firstDatabase, endpoint.getMongoDatabase());
+
+        endpoint.stop();
+        assertClosed(secondClient);
+    }
+
+    @Test
+    void clientsTheEndpointDidNotCreateAreNotClosed() throws Exception {
+        MongoClient beanClient = mock(MongoClient.class, RETURNS_DEEP_STUBS);
+        MongoClient optionClient = mock(MongoClient.class, RETURNS_DEEP_STUBS);
+        MongoClient componentClient = mock(MongoClient.class, 
RETURNS_DEEP_STUBS);
+        context.getRegistry().bind("beanClient", beanClient);
+        context.getRegistry().bind("optionClient", optionClient);
+
+        // added before the component has a client, which it would use ahead 
of the bean named by the path
+        String beanUri = 
"mongodb:beanClient?database=test&collection=test&operation=findAll";
+        addRoute("bean", beanUri);
+        context.getComponent("mongodb", 
MongoDbComponent.class).setMongoConnection(componentClient);
+        String optionUri = URI_ENDPOINT + "&mongoConnection=#optionClient";
+        addRoute("option", optionUri);
+        String componentUri = 
"mongodb:dummy?database=test&collection=test&operation=findAll";
+        addRoute("component", componentUri);
+
+        assertSame(beanClient, context.getEndpoint(beanUri, 
MongoDbEndpoint.class).getMongoConnection());
+        assertSame(optionClient, context.getEndpoint(optionUri, 
MongoDbEndpoint.class).getMongoConnection());
+        assertSame(componentClient, context.getEndpoint(componentUri, 
MongoDbEndpoint.class).getMongoConnection());
+        for (String routeId : new String[] { "bean", "option", "component" }) {
+            context.getRouteController().stopRoute(routeId);
+            assertTrue(context.removeRoute(routeId));
+        }
+        context.stop();
+
+        verify(beanClient, never()).close();
+        verify(optionClient, never()).close();
+        verify(componentClient, never()).close();
+    }
+
+    private void assertClientClosedWhenTheRouteIsRemoved(String uri) throws 
Exception {
+        addRoute("mongo", uri);
+        MongoDbEndpoint endpoint = context.getEndpoint(uri, 
MongoDbEndpoint.class);
+        MongoClient client = endpoint.getMongoConnection();
+        assertNotNull(client);
+
+        context.getRouteController().stopRoute("mongo");
+        assertTrue(context.removeRoute("mongo"));
+
+        assertTrue(endpoint.isStopped());
+        assertClosed(client);
+    }
+
+    private void addRoute(String routeId, String uri) throws Exception {
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:" + routeId).routeId(routeId).to(uri);
+            }
+        });
+    }
+
+    private static void assertClosed(MongoClient client) {
+        // a closed client fails at once, before it looks for a server
+        assertThrows(IllegalStateException.class, () -> 
client.listDatabaseNames().first());
+    }
+}
diff --git 
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbEndpointConnectionUriStringTest.java
 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbEndpointConnectionUriStringTest.java
new file mode 100644
index 000000000000..6115718d9dc8
--- /dev/null
+++ 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbEndpointConnectionUriStringTest.java
@@ -0,0 +1,96 @@
+/*
+ * 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 com.mongodb.ReadPreference;
+import com.mongodb.client.MongoClient;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.mockito.Mockito.mock;
+
+/**
+ * Which client a mongodb endpoint uses when it has a connectionUriString, a 
client in the registry, or both.
+ */
+class MongoDbEndpointConnectionUriStringTest extends CamelTestSupport {
+
+    private static final String URI_ENDPOINT
+            = 
"mongodb:dummy?connectionUriString=RAW(mongodb://localhost:27017/?readPreference=secondaryPreferred)"
+              + "&database=test&collection=test&operation=findAll";
+
+    @Test
+    void connectionUriStringIsUsedInsteadOfTheClientOfTheComponent() {
+        MongoClient registryClient = mock(MongoClient.class);
+        context.getRegistry().bind("registryClient", registryClient);
+
+        MongoDbEndpoint endpoint = context.getEndpoint(URI_ENDPOINT, 
MongoDbEndpoint.class);
+
+        MongoClient client = endpoint.getMongoConnection();
+        assertNotSame(registryClient, client);
+        assertEquals(ReadPreference.secondaryPreferred(), 
client.getReadPreference());
+    }
+
+    @Test
+    void connectionUriStringIsUsedWhenNoClientIsInTheRegistry() {
+        MongoDbEndpoint endpoint = context.getEndpoint(URI_ENDPOINT, 
MongoDbEndpoint.class);
+
+        MongoClient client = endpoint.getMongoConnection();
+        assertNotNull(client);
+        assertEquals(ReadPreference.secondaryPreferred(), 
client.getReadPreference());
+    }
+
+    @Test
+    void connectionBeanIsUsedWithoutConnectionUriStringAndHosts() {
+        MongoClient firstClient = mock(MongoClient.class);
+        MongoClient secondClient = mock(MongoClient.class);
+        context.getRegistry().bind("firstClient", firstClient);
+        context.getRegistry().bind("secondClient", secondClient);
+
+        MongoDbEndpoint endpoint = context.getEndpoint(
+                
"mongodb:secondClient?database=test&collection=test&operation=findAll", 
MongoDbEndpoint.class);
+
+        assertSame(secondClient, endpoint.getMongoConnection());
+    }
+
+    @Test
+    void clientOfTheComponentIsUsedWithoutConnectionUriStringAndHosts() {
+        MongoClient registryClient = mock(MongoClient.class);
+        context.getRegistry().bind("registryClient", registryClient);
+
+        MongoDbEndpoint endpoint = context.getEndpoint(
+                
"mongodb:dummy?database=test&collection=test&operation=findAll", 
MongoDbEndpoint.class);
+
+        assertSame(registryClient, endpoint.getMongoConnection());
+    }
+
+    @Test
+    void mongoConnectionOptionIsUsedBeforeConnectionUriString() {
+        MongoClient explicitClient = mock(MongoClient.class);
+        MongoClient otherClient = mock(MongoClient.class);
+        context.getRegistry().bind("explicitClient", explicitClient);
+        context.getRegistry().bind("otherClient", otherClient);
+
+        MongoDbEndpoint endpoint
+                = context.getEndpoint(URI_ENDPOINT + 
"&mongoConnection=#explicitClient", MongoDbEndpoint.class);
+
+        assertSame(explicitClient, endpoint.getMongoConnection());
+    }
+}
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 b70e68a1297f..9821bfdd4f17 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
@@ -6807,6 +6807,23 @@ The consumers now call `processCommit(Exchange, String)` 
with the name of the ob
 of `GoogleCloudStorageConsumer`, `MinioConsumer` or `MNSConsumer` that 
overrides `processCommit(Exchange)` must override
 the new method instead. `processCommit(Exchange)` is deprecated.
 
+=== camel-mongodb - connectionUriString without hosts creates the client of 
the endpoint
+
+An endpoint that sets `connectionUriString` without `hosts` now creates its 
client from the connection string. Before,
+the connection string was not used: the endpoint used the `MongoClient` of the 
component (autowired when the registry
+holds exactly one) or else the `MongoClient` bean named by the endpoint path, 
and failed to start when there was none.
+To keep using a client bean, remove `connectionUriString` from the endpoint.
+
+Each endpoint with `connectionUriString` or `hosts` creates its own client and 
connection pool, also when other
+endpoints (for example with another collection or operation) use the same 
connection string. To share one client
+between endpoints, bind a `MongoClient` and have the endpoints use it (the 
endpoint path or the `mongoConnection`
+option) instead of `connectionUriString` or `hosts`.
+
+The endpoint now closes the client it created when it stops, for example when 
its route is removed or reloaded, or when
+the `CamelContext` stops, and creates a new one when it is started again. 
Before, a client created from `hosts` stayed
+open. A client the endpoint did not create (the `mongoConnection` option, the 
client of the component, or the bean
+named by the endpoint path) is not closed.
+
 === 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-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MongodbComponentBuilderFactory.java
 
b/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MongodbComponentBuilderFactory.java
index a5c22d59daca..44bd5e6195da 100644
--- 
a/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MongodbComponentBuilderFactory.java
+++ 
b/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MongodbComponentBuilderFactory.java
@@ -52,7 +52,8 @@ public interface MongodbComponentBuilderFactory {
     
         /**
          * Shared client used for connection. All endpoints generated from the
-         * component will share this connection client.
+         * component will share this connection client, except the endpoints
+         * that set hosts or connectionUriString, which create their own 
client.
          * 
          * The option is a:
          * &lt;code&gt;com.mongodb.client.MongoClient&lt;/code&gt; type.
diff --git 
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/StaticEndpointBuilders.java
 
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/StaticEndpointBuilders.java
index 9e756afe0d11..b8602a81ad29 100644
--- 
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/StaticEndpointBuilders.java
+++ 
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/StaticEndpointBuilders.java
@@ -12520,7 +12520,8 @@ public class StaticEndpointBuilders {
      * 
      * Path parameter: connectionBean (required)
      * Sets the connection bean reference used to lookup a client for 
connecting
-     * to a database if no hosts parameter is present.
+     * to a database if neither the hosts nor the connectionUriString parameter
+     * is present.
      * 
      * @param path connectionBean
      * @return the dsl builder
@@ -12540,7 +12541,8 @@ public class StaticEndpointBuilders {
      * 
      * Path parameter: connectionBean (required)
      * Sets the connection bean reference used to lookup a client for 
connecting
-     * to a database if no hosts parameter is present.
+     * to a database if neither the hosts nor the connectionUriString parameter
+     * is present.
      * 
      * @param componentName to use a custom component name for the endpoint
      * instead of the default name
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 51ca4f31450b..68894cc94327 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
@@ -73,7 +73,9 @@ public interface MongoDbEndpointBuilderFactory {
             return this;
         }
         /**
-         * Set the whole Connection String/Uri for mongodb endpoint.
+         * Set the whole Connection String/Uri for mongodb endpoint. When set,
+         * the endpoint creates its client from it, instead of using the client
+         * of the component or the connectionBean.
          * 
          * The option is a: <code>java.lang.String</code> type.
          * 
@@ -1652,7 +1654,9 @@ public interface MongoDbEndpointBuilderFactory {
             return this;
         }
         /**
-         * Set the whole Connection String/Uri for mongodb endpoint.
+         * Set the whole Connection String/Uri for mongodb endpoint. When set,
+         * the endpoint creates its client from it, instead of using the client
+         * of the component or the connectionBean.
          * 
          * The option is a: <code>java.lang.String</code> type.
          * 
@@ -2929,7 +2933,9 @@ public interface MongoDbEndpointBuilderFactory {
             return this;
         }
         /**
-         * Set the whole Connection String/Uri for mongodb endpoint.
+         * Set the whole Connection String/Uri for mongodb endpoint. When set,
+         * the endpoint creates its client from it, instead of using the client
+         * of the component or the connectionBean.
          * 
          * The option is a: <code>java.lang.String</code> type.
          * 
@@ -4148,7 +4154,8 @@ public interface MongoDbEndpointBuilderFactory {
          * 
          * Path parameter: connectionBean (required)
          * Sets the connection bean reference used to lookup a client for
-         * connecting to a database if no hosts parameter is present.
+         * connecting to a database if neither the hosts nor the
+         * connectionUriString parameter is present.
          * 
          * @param path connectionBean
          * @return the dsl builder
@@ -4168,7 +4175,8 @@ public interface MongoDbEndpointBuilderFactory {
          * 
          * Path parameter: connectionBean (required)
          * Sets the connection bean reference used to lookup a client for
-         * connecting to a database if no hosts parameter is present.
+         * connecting to a database if neither the hosts nor the
+         * connectionUriString parameter is present.
          * 
          * @param componentName to use a custom component name for the endpoint
          * instead of the default name

Reply via email to