0
# Client and Connection Management
1
2
Core client functionality for establishing mock MongoDB connections and managing database access. The MongoClient class serves as the main entry point for all database operations.
3
4
## Capabilities
5
6
### MongoClient Creation
7
8
Create mock MongoDB client instances with configurable connection parameters that mirror PyMongo's client interface.
9
10
```python { .api }
11
class MongoClient:
12
def __init__(self, host=None, port=None, document_class=dict,
13
tz_aware=False, connect=True, _store=None,
14
read_preference=None, **kwargs):
15
"""
16
Create a mock MongoDB client.
17
18
Parameters:
19
- host: str or list, MongoDB server host(s) (ignored in mock)
20
- port: int, MongoDB server port (ignored in mock)
21
- document_class: type, class for documents (default: dict)
22
- tz_aware: bool, timezone-aware datetime handling
23
- connect: bool, immediate connection attempt (ignored in mock)
24
- read_preference: ReadPreference, read preference setting
25
- **kwargs: additional connection parameters
26
27
Returns:
28
MongoClient instance
29
"""
30
```
31
32
**Usage Example:**
33
34
```python
35
import mongomock
36
37
# Basic client
38
client = mongomock.MongoClient()
39
40
# Client with custom configuration
41
client = mongomock.MongoClient(
42
host='localhost',
43
port=27017,
44
tz_aware=True,
45
document_class=dict
46
)
47
48
# Client with connection string (parsed but ignored)
49
client = mongomock.MongoClient('mongodb://localhost:27017/testdb')
50
```
51
52
### Database Access
53
54
Access databases through the client with support for default database retrieval and database listing.
55
56
```python { .api }
57
def get_database(self, name=None, codec_options=None,
58
read_preference=None, write_concern=None,
59
read_concern=None):
60
"""
61
Get a database instance.
62
63
Parameters:
64
- name: str, database name (optional if default set)
65
- codec_options: CodecOptions, encoding/decoding options
66
- read_preference: ReadPreference, read preference override
67
- write_concern: WriteConcern, write concern override
68
- read_concern: ReadConcern, read concern override
69
70
Returns:
71
Database instance
72
"""
73
74
def get_default_database(self, default=None, **kwargs):
75
"""
76
Get the default database.
77
78
Parameters:
79
- default: str, default database name if none configured
80
- **kwargs: additional database options
81
82
Returns:
83
Database instance
84
85
Raises:
86
ConfigurationError: if no default database configured
87
"""
88
89
def list_database_names(self):
90
"""
91
List all database names.
92
93
Returns:
94
List[str]: list of database names
95
"""
96
```
97
98
**Usage Example:**
99
100
```python
101
client = mongomock.MongoClient()
102
103
# Get database by name
104
db = client.get_database('testdb')
105
db = client['testdb'] # Alternative syntax
106
db = client.testdb # Alternative syntax
107
108
# Get default database (if configured)
109
db = client.get_default_database()
110
111
# List all databases
112
databases = client.list_database_names()
113
```
114
115
### Database Management
116
117
Drop databases and manage database lifecycle operations.
118
119
```python { .api }
120
def drop_database(self, name_or_db):
121
"""
122
Drop a database.
123
124
Parameters:
125
- name_or_db: str or Database, database name or instance
126
127
Returns:
128
None
129
"""
130
```
131
132
**Usage Example:**
133
134
```python
135
client = mongomock.MongoClient()
136
137
# Create and populate database
138
db = client.testdb
139
db.collection.insert_one({'test': 'data'})
140
141
# Drop database
142
client.drop_database('testdb')
143
# or
144
client.drop_database(db)
145
```
146
147
### Server Information
148
149
Retrieve mock server information and connection status.
150
151
```python { .api }
152
def server_info(self):
153
"""
154
Get server information.
155
156
Returns:
157
Dict[str, Any]: server information dictionary
158
"""
159
160
def alive(self):
161
"""
162
Check if client connection is alive.
163
164
Returns:
165
bool: always True for mock client
166
"""
167
168
def close(self):
169
"""
170
Close client connection.
171
172
Returns:
173
None
174
"""
175
176
def start_session(self, causal_consistency=True, default_transaction_options=None):
177
"""
178
Start a client session (raises NotImplementedError).
179
180
Parameters:
181
- causal_consistency: bool, enable causal consistency
182
- default_transaction_options: TransactionOptions, default transaction options
183
184
Returns:
185
ClientSession: session object
186
187
Raises:
188
NotImplementedError: sessions not implemented in mongomock
189
"""
190
```
191
192
**Usage Example:**
193
194
```python
195
client = mongomock.MongoClient()
196
197
# Get server information
198
info = client.server_info()
199
print(info['version']) # Mock server version
200
201
# Check connection status
202
is_alive = client.alive() # Always True
203
204
# Close connection
205
client.close()
206
```
207
208
### Client Properties
209
210
Access client configuration and connection information.
211
212
```python { .api }
213
@property
214
def host(self):
215
"""str: server host"""
216
217
@property
218
def port(self):
219
"""int: server port"""
220
221
@property
222
def address(self):
223
"""tuple: (host, port) address tuple"""
224
225
@property
226
def read_preference(self):
227
"""ReadPreference: current read preference"""
228
229
@property
230
def codec_options(self):
231
"""CodecOptions: current codec options"""
232
233
@property
234
def is_mongos(self):
235
"""bool: whether connected to mongos (always True)"""
236
237
@property
238
def is_primary(self):
239
"""bool: whether connected to primary (always True)"""
240
```
241
242
**Usage Example:**
243
244
```python
245
client = mongomock.MongoClient('localhost', 27017)
246
247
print(f"Connected to {client.host}:{client.port}")
248
print(f"Address: {client.address}")
249
print(f"Is primary: {client.is_primary}")
250
print(f"Read preference: {client.read_preference}")
251
```
252
253
## Constants
254
255
```python { .api }
256
HOST = 'localhost' # Default host
257
PORT = 27017 # Default port
258
```