0
# Connection Management
1
2
Factory methods and client interfaces for establishing and managing MongoDB connections with various configuration options.
3
4
## Capabilities
5
6
### MongoClients Factory
7
8
Factory class providing static methods to create `MongoClient` instances with different configuration approaches.
9
10
```java { .api }
11
/**
12
* Factory for MongoClient instances
13
*/
14
public final class MongoClients {
15
/**
16
* Creates a client with default connection string "mongodb://localhost:27017"
17
* @return the MongoDB client
18
*/
19
public static MongoClient create();
20
21
/**
22
* Creates a client with the given connection string
23
* @param connectionString the MongoDB connection string
24
* @return the MongoDB client
25
*/
26
public static MongoClient create(String connectionString);
27
28
/**
29
* Creates a client with the given connection string object
30
* @param connectionString the MongoDB ConnectionString object
31
* @return the MongoDB client
32
*/
33
public static MongoClient create(ConnectionString connectionString);
34
35
/**
36
* Creates a client with detailed settings
37
* @param settings the MongoDB client settings
38
* @return the MongoDB client
39
*/
40
public static MongoClient create(MongoClientSettings settings);
41
42
/**
43
* Creates a client with connection string and driver information
44
* @param connectionString the MongoDB connection string
45
* @param mongoDriverInformation optional driver metadata
46
* @return the MongoDB client
47
*/
48
public static MongoClient create(ConnectionString connectionString,
49
MongoDriverInformation mongoDriverInformation);
50
51
/**
52
* Creates a client with settings and driver information
53
* @param settings the MongoDB client settings
54
* @param mongoDriverInformation optional driver metadata
55
* @return the MongoDB client
56
*/
57
public static MongoClient create(MongoClientSettings settings,
58
MongoDriverInformation mongoDriverInformation);
59
}
60
```
61
62
**Usage Examples:**
63
64
```java
65
import com.mongodb.client.MongoClient;
66
import com.mongodb.client.MongoClients;
67
import com.mongodb.MongoClientSettings;
68
import com.mongodb.ConnectionString;
69
70
// Default localhost connection
71
MongoClient client1 = MongoClients.create();
72
73
// Connection string
74
MongoClient client2 = MongoClients.create("mongodb://user:pass@host:27017/mydb");
75
76
// ConnectionString object with options
77
ConnectionString connString = new ConnectionString("mongodb://host:27017");
78
MongoClient client3 = MongoClients.create(connString);
79
80
// Detailed settings
81
MongoClientSettings settings = MongoClientSettings.builder()
82
.applyConnectionString(new ConnectionString("mongodb://host:27017"))
83
.readPreference(ReadPreference.secondary())
84
.writeConcern(WriteConcern.MAJORITY)
85
.build();
86
MongoClient client4 = MongoClients.create(settings);
87
```
88
89
### MongoClient Interface
90
91
Main client interface extending `MongoCluster` and providing connection lifecycle management.
92
93
```java { .api }
94
/**
95
* Main MongoDB client interface for connection management
96
*/
97
public interface MongoClient extends MongoCluster, AutoCloseable {
98
/**
99
* Releases all resources associated with this client
100
*/
101
void close();
102
103
/**
104
* Gets information about the cluster this client is connected to
105
* @return cluster description containing server information
106
*/
107
ClusterDescription getClusterDescription();
108
}
109
```
110
111
**Usage Examples:**
112
113
```java
114
import com.mongodb.client.MongoClient;
115
import com.mongodb.client.MongoClients;
116
import com.mongodb.connection.ClusterDescription;
117
118
// Create and use client
119
try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {
120
// Get cluster information
121
ClusterDescription cluster = client.getClusterDescription();
122
System.out.println("Connected to: " + cluster.getServerDescriptions());
123
124
// Use client for operations...
125
MongoDatabase db = client.getDatabase("mydb");
126
127
} // Automatically closes connection
128
```
129
130
### MongoCluster Interface
131
132
Base interface providing cluster-level operations accessible through `MongoClient`.
133
134
```java { .api }
135
/**
136
* Interface for cluster-level MongoDB operations
137
*/
138
public interface MongoCluster {
139
/**
140
* Gets a database instance for the given name
141
* @param databaseName the name of the database
142
* @return MongoDatabase instance
143
*/
144
MongoDatabase getDatabase(String databaseName);
145
146
/**
147
* Starts a new client session with default options
148
* @return ClientSession for transaction and consistency support
149
*/
150
ClientSession startSession();
151
152
/**
153
* Starts a new client session with specific options
154
* @param options session configuration options
155
* @return ClientSession for transaction and consistency support
156
*/
157
ClientSession startSession(ClientSessionOptions options);
158
159
/**
160
* Lists all database names
161
* @return iterable of database names
162
*/
163
MongoIterable<String> listDatabaseNames();
164
165
/**
166
* Lists databases with detailed information
167
* @return iterable of database documents with metadata
168
*/
169
ListDatabasesIterable<Document> listDatabases();
170
171
/**
172
* Lists databases with detailed information as specified type
173
* @param clazz the class to decode each database document to
174
* @return iterable of database information objects
175
*/
176
<TResult> ListDatabasesIterable<TResult> listDatabases(Class<TResult> clazz);
177
178
/**
179
* Creates a change stream to monitor cluster-level changes
180
* @return change stream iterable for all databases
181
*/
182
ChangeStreamIterable<Document> watch();
183
184
/**
185
* Creates a change stream with aggregation pipeline
186
* @param pipeline aggregation pipeline to filter changes
187
* @return change stream iterable with filtering
188
*/
189
ChangeStreamIterable<Document> watch(List<? extends Bson> pipeline);
190
191
/**
192
* Creates a change stream with specific result type
193
* @param pipeline aggregation pipeline to filter changes
194
* @param clazz the class to decode each change document to
195
* @return change stream iterable with custom type
196
*/
197
<TResult> ChangeStreamIterable<TResult> watch(List<? extends Bson> pipeline, Class<TResult> clazz);
198
}
199
```
200
201
**Usage Examples:**
202
203
```java
204
import com.mongodb.client.MongoClient;
205
import com.mongodb.client.MongoClients;
206
import com.mongodb.client.MongoDatabase;
207
import com.mongodb.client.ClientSession;
208
209
try (MongoClient client = MongoClients.create()) {
210
// Get database
211
MongoDatabase database = client.getDatabase("myapp");
212
213
// List all databases
214
for (String dbName : client.listDatabaseNames()) {
215
System.out.println("Database: " + dbName);
216
}
217
218
// Start session for transactions
219
try (ClientSession session = client.startSession()) {
220
// Use session for transactional operations...
221
}
222
223
// Monitor cluster-wide changes
224
try (var cursor = client.watch().cursor()) {
225
while (cursor.hasNext()) {
226
System.out.println("Change detected: " + cursor.next());
227
}
228
}
229
}
230
```
231
232
### Configuration Options
233
234
The driver supports various configuration approaches for different use cases.
235
236
```java { .api }
237
// Configuration with MongoClientSettings
238
MongoClientSettings settings = MongoClientSettings.builder()
239
.applyConnectionString(new ConnectionString("mongodb://host:27017"))
240
.readPreference(ReadPreference.primaryPreferred())
241
.writeConcern(WriteConcern.MAJORITY)
242
.readConcern(ReadConcern.SNAPSHOT)
243
.codecRegistry(CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()))
244
.build();
245
246
// Configuration with connection string options
247
String connStr = "mongodb://host:27017/mydb?" +
248
"readPreference=secondary&" +
249
"writeConcern=majority&" +
250
"readConcernLevel=snapshot&" +
251
"maxPoolSize=50";
252
```
253
254
### MongoClientFactory
255
256
ObjectFactory implementation for dependency injection frameworks.
257
258
```java { .api }
259
/**
260
* ObjectFactory for creating MongoClient instances in DI containers
261
*/
262
public class MongoClientFactory implements ObjectFactory<MongoClient> {
263
/**
264
* Creates a MongoClient instance for dependency injection
265
* @return MongoClient instance
266
*/
267
@Override
268
public MongoClient getObject();
269
}
270
```