0
# Client and Connection Management
1
2
MongoDB client creation, connection management, authentication, and configuration options including connection pooling, timeouts, and replica set support.
3
4
## Capabilities
5
6
### MongoClient Creation
7
8
Create and configure MongoDB client connections with various options for production deployments.
9
10
```python { .api }
11
class MongoClient:
12
def __init__(
13
self,
14
host='localhost',
15
port=27017,
16
document_class=dict,
17
tz_aware=False,
18
connect=True,
19
type_registry=None,
20
**kwargs
21
):
22
"""
23
Create a MongoDB client.
24
25
Parameters:
26
- host: hostname or IP address, or MongoDB URI
27
- port: port number
28
- document_class: default class to use for documents
29
- tz_aware: if True, datetime instances are timezone-aware
30
- connect: if True, immediately connect to MongoDB
31
- maxPoolSize: maximum number of connections per pool
32
- minPoolSize: minimum number of connections per pool
33
- maxIdleTimeMS: maximum idle time for pooled connections
34
- waitQueueTimeoutMS: timeout for waiting for available connection
35
- serverSelectionTimeoutMS: timeout for server selection
36
- socketTimeoutMS: timeout for socket operations
37
- ssl: enable SSL/TLS connection
38
- username: authentication username
39
- password: authentication password
40
- authSource: database to authenticate against
41
- authMechanism: authentication mechanism
42
"""
43
```
44
45
### Database Access
46
47
Access databases and manage database-level operations.
48
49
```python { .api }
50
class MongoClient:
51
def get_database(self, name, **kwargs):
52
"""
53
Get a database instance.
54
55
Parameters:
56
- name: database name
57
- codec_options: BSON codec options
58
- read_preference: read preference for operations
59
- write_concern: write concern for operations
60
- read_concern: read concern for operations
61
62
Returns:
63
Database instance
64
"""
65
66
def list_database_names(self, session=None, **kwargs):
67
"""
68
List database names.
69
70
Parameters:
71
- session: optional ClientSession
72
73
Returns:
74
List of database names
75
"""
76
77
def list_databases(self, session=None, **kwargs):
78
"""
79
List databases with metadata.
80
81
Parameters:
82
- session: optional ClientSession
83
84
Returns:
85
Command cursor with database information
86
"""
87
```
88
89
### Connection Management
90
91
Manage client connections and server information.
92
93
```python { .api }
94
class MongoClient:
95
def close(self):
96
"""Close all connections in the connection pools."""
97
98
def server_info(self, session=None):
99
"""
100
Get server version and build information.
101
102
Parameters:
103
- session: optional ClientSession
104
105
Returns:
106
dict: Server information
107
"""
108
109
@property
110
def address(self):
111
"""
112
Primary server address as (host, port) tuple.
113
114
Returns:
115
tuple: (host, port) or None if not connected
116
"""
117
118
@property
119
def primary(self):
120
"""
121
Primary server address.
122
123
Returns:
124
tuple: (host, port) or None for standalone
125
"""
126
127
@property
128
def secondaries(self):
129
"""
130
Secondary server addresses.
131
132
Returns:
133
set: Set of (host, port) tuples
134
"""
135
136
@property
137
def arbiters(self):
138
"""
139
Arbiter server addresses.
140
141
Returns:
142
set: Set of (host, port) tuples
143
"""
144
```
145
146
### Session Management
147
148
Create and manage client sessions for transactions and consistency.
149
150
```python { .api }
151
class MongoClient:
152
def start_session(
153
self,
154
causal_consistency=None,
155
default_transaction_options=None,
156
snapshot=False
157
):
158
"""
159
Start a client session.
160
161
Parameters:
162
- causal_consistency: enable causal consistency
163
- default_transaction_options: default transaction options
164
- snapshot: enable snapshot reads
165
166
Returns:
167
ClientSession instance
168
"""
169
170
class ClientSession:
171
def end_session(self):
172
"""End the session and return connection to pool."""
173
174
@property
175
def session_id(self):
176
"""
177
Session identifier.
178
179
Returns:
180
dict: Session ID document
181
"""
182
183
@property
184
def cluster_time(self):
185
"""
186
Cluster time for causal consistency.
187
188
Returns:
189
dict: Cluster time document
190
"""
191
192
@property
193
def operation_time(self):
194
"""
195
Operation time for causal consistency.
196
197
Returns:
198
Timestamp: Operation time
199
"""
200
201
def advance_cluster_time(self, cluster_time):
202
"""
203
Advance cluster time.
204
205
Parameters:
206
- cluster_time: cluster time document
207
"""
208
209
def advance_operation_time(self, operation_time):
210
"""
211
Advance operation time.
212
213
Parameters:
214
- operation_time: operation timestamp
215
"""
216
```
217
218
## Usage Examples
219
220
### Basic Connection
221
222
```python
223
from pymongo import MongoClient
224
225
# Connect to local MongoDB
226
client = MongoClient()
227
228
# Connect with custom host/port
229
client = MongoClient('mongodb://example.com:27017/')
230
231
# Connect with authentication
232
client = MongoClient(
233
'mongodb://username:password@example.com:27017/mydb'
234
)
235
```
236
237
### Connection Pooling
238
239
```python
240
from pymongo import MongoClient
241
242
# Configure connection pool
243
client = MongoClient(
244
'mongodb://example.com:27017/',
245
maxPoolSize=50,
246
minPoolSize=10,
247
maxIdleTimeMS=30000,
248
waitQueueTimeoutMS=5000
249
)
250
```
251
252
### SSL/TLS Connection
253
254
```python
255
from pymongo import MongoClient
256
257
# Enable SSL
258
client = MongoClient(
259
'mongodb://example.com:27017/',
260
ssl=True,
261
ssl_ca_certs='/path/to/ca.pem',
262
ssl_certfile='/path/to/client.pem'
263
)
264
```
265
266
### Working with Sessions
267
268
```python
269
from pymongo import MongoClient
270
271
client = MongoClient()
272
db = client.mydb
273
collection = db.mycollection
274
275
# Use session for causal consistency
276
with client.start_session(causal_consistency=True) as session:
277
collection.insert_one({"name": "Alice"}, session=session)
278
doc = collection.find_one({"name": "Alice"}, session=session)
279
```