0
# Configuration and Options
1
2
Configuration classes for controlling read/write behavior, codec options, and database connection parameters. These classes provide fine-grained control over MongoDB operations and data handling.
3
4
## Capabilities
5
6
### Write Concerns
7
8
Control write operation acknowledgment and durability requirements.
9
10
```python { .api }
11
class WriteConcern:
12
def __init__(self, w=None, wtimeout=None, j=None, fsync=None):
13
"""
14
Create a write concern specification.
15
16
Parameters:
17
- w: int or str, write acknowledgment requirement
18
- int: number of replica set members to acknowledge
19
- str: 'majority' for majority acknowledgment
20
- wtimeout: int, timeout in milliseconds for write concern
21
- j: bool, require journal acknowledgment
22
- fsync: bool, require fsync before acknowledgment
23
24
Returns:
25
WriteConcern instance
26
"""
27
28
@property
29
def acknowledged(self):
30
"""bool: whether write operations are acknowledged"""
31
32
@property
33
def document(self):
34
"""dict: write concern as document"""
35
36
@property
37
def is_server_default(self):
38
"""bool: whether this is the server default write concern"""
39
```
40
41
**Usage Example:**
42
43
```python
44
from mongomock import WriteConcern
45
46
# Default acknowledged write
47
wc_default = WriteConcern()
48
49
# Require acknowledgment from majority of replica set
50
wc_majority = WriteConcern(w='majority')
51
52
# Require acknowledgment from specific number of members
53
wc_three = WriteConcern(w=3, wtimeout=5000)
54
55
# Require journal acknowledgment
56
wc_journal = WriteConcern(j=True)
57
58
# Use with collection operations
59
collection = mongomock.MongoClient().db.collection.with_options(
60
write_concern=wc_majority
61
)
62
63
result = collection.insert_one({'data': 'value'})
64
print(f"Acknowledged: {result.acknowledged}")
65
```
66
67
### Read Concerns
68
69
Specify read isolation and consistency requirements.
70
71
```python { .api }
72
class ReadConcern:
73
def __init__(self, level=None):
74
"""
75
Create a read concern specification.
76
77
Parameters:
78
- level: str, read concern level
79
- 'local': return most recent data (default)
80
- 'available': return available data without consistency guarantee
81
- 'majority': return data acknowledged by majority
82
- 'linearizable': return data that reflects all writes
83
- 'snapshot': return consistent snapshot
84
85
Returns:
86
ReadConcern instance
87
"""
88
89
@property
90
def level(self):
91
"""str: read concern level"""
92
93
@property
94
def ok_for_legacy(self):
95
"""bool: whether compatible with legacy servers"""
96
97
@property
98
def document(self):
99
"""dict: read concern as document"""
100
```
101
102
**Usage Example:**
103
104
```python
105
from mongomock import ReadConcern
106
107
# Default local read concern
108
rc_local = ReadConcern()
109
rc_local = ReadConcern(level='local')
110
111
# Majority read concern for consistency
112
rc_majority = ReadConcern(level='majority')
113
114
# Linearizable read concern for strongest consistency
115
rc_linear = ReadConcern(level='linearizable')
116
117
# Use with database/collection operations
118
db = mongomock.MongoClient().get_database('test', read_concern=rc_majority)
119
collection = db.collection
120
121
# Query with read concern
122
documents = list(collection.find({'status': 'active'}))
123
```
124
125
### Codec Options
126
127
Configure document encoding, decoding, and type handling.
128
129
```python { .api }
130
class CodecOptions:
131
def __init__(self, document_class=dict, tz_aware=False,
132
uuid_representation=0, unicode_decode_error_handler="strict",
133
tzinfo=None, type_registry=None, datetime_conversion=None):
134
"""
135
Create codec options for BSON encoding/decoding.
136
137
Parameters:
138
- document_class: type, class to use for documents (default: dict)
139
- tz_aware: bool, decode dates as timezone-aware datetimes
140
- uuid_representation: int, UUID representation format
141
- unicode_decode_error_handler: str, unicode error handling
142
- tzinfo: timezone, timezone for datetime objects
143
- type_registry: TypeRegistry, custom type registry
144
- datetime_conversion: DatetimeConversion, datetime conversion mode
145
146
Returns:
147
CodecOptions instance
148
"""
149
150
def with_options(self, **kwargs):
151
"""
152
Create new CodecOptions with updated options.
153
154
Parameters:
155
- **kwargs: options to update
156
157
Returns:
158
CodecOptions: new instance with updated options
159
"""
160
161
@property
162
def document_class(self):
163
"""type: document class"""
164
165
@property
166
def tz_aware(self):
167
"""bool: timezone awareness setting"""
168
169
@property
170
def uuid_representation(self):
171
"""int: UUID representation format"""
172
```
173
174
**Usage Example:**
175
176
```python
177
from mongomock import CodecOptions
178
from collections import OrderedDict
179
import pytz
180
181
# Default codec options (dict documents)
182
codec_default = CodecOptions()
183
184
# Use OrderedDict to preserve field order
185
codec_ordered = CodecOptions(document_class=OrderedDict)
186
187
# Timezone-aware datetime handling
188
codec_tz = CodecOptions(tz_aware=True, tzinfo=pytz.UTC)
189
190
# Custom unicode error handling
191
codec_unicode = CodecOptions(unicode_decode_error_handler='ignore')
192
193
# Combine options
194
codec_custom = CodecOptions(
195
document_class=OrderedDict,
196
tz_aware=True,
197
tzinfo=pytz.timezone('US/Eastern'),
198
unicode_decode_error_handler='replace'
199
)
200
201
# Use with client/database/collection
202
client = mongomock.MongoClient()
203
db = client.get_database('test', codec_options=codec_custom)
204
205
# Update codec options
206
new_codec = codec_custom.with_options(tz_aware=False)
207
updated_db = db.with_options(codec_options=new_codec)
208
```
209
210
### Read Preferences
211
212
Control read routing and server selection behavior.
213
214
```python { .api }
215
# Read preference constants (from mongomock.read_preferences)
216
PRIMARY = 0 # Read from primary only
217
PRIMARY_PREFERRED = 1 # Prefer primary, fallback to secondary
218
SECONDARY = 2 # Read from secondary only
219
SECONDARY_PREFERRED = 3 # Prefer secondary, fallback to primary
220
NEAREST = 4 # Read from nearest server
221
```
222
223
**Usage Example:**
224
225
```python
226
from mongomock import read_preferences
227
228
# Use read preferences with client
229
client = mongomock.MongoClient(read_preference=read_preferences.SECONDARY)
230
231
# Use with database
232
db = client.get_database('test',
233
read_preference=read_preferences.PRIMARY_PREFERRED
234
)
235
236
# Use with collection
237
collection = db.get_collection('users',
238
read_preference=read_preferences.NEAREST
239
)
240
241
# Query with specific read preference
242
primary_results = list(collection.with_options(
243
read_preference=read_preferences.PRIMARY
244
).find({'status': 'active'}))
245
```
246
247
### Connection Configuration
248
249
Configure client connection behavior and options.
250
251
**Client Configuration Options:**
252
253
```python
254
# Connection string parsing
255
client = mongomock.MongoClient('mongodb://localhost:27017/testdb')
256
257
# Individual parameters
258
client = mongomock.MongoClient(
259
host='localhost',
260
port=27017,
261
document_class=OrderedDict,
262
tz_aware=True,
263
connect=True
264
)
265
266
# Advanced configuration
267
client = mongomock.MongoClient(
268
host=['server1:27017', 'server2:27017'], # Multiple hosts
269
read_preference=read_preferences.SECONDARY_PREFERRED,
270
write_concern=WriteConcern(w='majority'),
271
read_concern=ReadConcern(level='majority')
272
)
273
```
274
275
**Database and Collection Configuration:**
276
277
```python
278
# Database with options
279
db = client.get_database('mydb',
280
codec_options=CodecOptions(tz_aware=True),
281
read_preference=read_preferences.SECONDARY,
282
write_concern=WriteConcern(w=2),
283
read_concern=ReadConcern(level='majority')
284
)
285
286
# Collection with options
287
collection = db.get_collection('mycol',
288
codec_options=CodecOptions(document_class=OrderedDict),
289
read_preference=read_preferences.PRIMARY
290
)
291
292
# Chain configuration
293
configured_collection = (
294
client
295
.get_database('mydb', read_concern=ReadConcern(level='majority'))
296
.get_collection('mycol', write_concern=WriteConcern(w='majority'))
297
)
298
```
299
300
### Configuration Inheritance
301
302
Understand how configuration options are inherited through the hierarchy.
303
304
**Configuration Hierarchy:**
305
306
```
307
MongoClient
308
↓ (inherits client options)
309
Database
310
↓ (inherits database options, can override)
311
Collection
312
↓ (inherits collection options, can override)
313
Operation
314
```
315
316
**Usage Example:**
317
318
```python
319
from mongomock import MongoClient, WriteConcern, ReadConcern, CodecOptions
320
321
# Client-level configuration
322
client = MongoClient(
323
tz_aware=True,
324
read_preference=read_preferences.SECONDARY_PREFERRED
325
)
326
327
# Database inherits client config, adds write concern
328
db = client.get_database('mydb',
329
write_concern=WriteConcern(w='majority')
330
)
331
332
# Collection inherits db config, overrides read preference
333
collection = db.get_collection('mycol',
334
read_preference=read_preferences.PRIMARY
335
)
336
337
# Operation-level override
338
result = collection.with_options(
339
write_concern=WriteConcern(w=1)
340
).insert_one({'data': 'value'})
341
```
342
343
### Environment Configuration
344
345
Configure behavior through environment variables and global settings.
346
347
```python { .api }
348
# Server version configuration
349
SERVER_VERSION = '5.0.5' # Default MongoDB version to simulate
350
351
# Environment variable support
352
import os
353
server_version = os.getenv('MONGODB', '5.0.5')
354
```
355
356
**Usage Example:**
357
358
```python
359
import os
360
import mongomock
361
362
# Set server version via environment
363
os.environ['MONGODB'] = '6.0.0'
364
365
# Create client with environment settings
366
client = mongomock.MongoClient()
367
368
# Check server info
369
info = client.server_info()
370
print(f"Simulated MongoDB version: {info.get('version')}")
371
372
# Global server version setting
373
mongomock.SERVER_VERSION = '4.4.0'
374
375
# All new clients will use this version
376
new_client = mongomock.MongoClient()
377
```
378
379
## Configuration Best Practices
380
381
**Production-Like Testing:**
382
383
```python
384
# Mirror production configuration in tests
385
production_config = {
386
'write_concern': WriteConcern(w='majority', j=True),
387
'read_concern': ReadConcern(level='majority'),
388
'read_preference': read_preferences.SECONDARY_PREFERRED
389
}
390
391
# Test client with production settings
392
test_client = mongomock.MongoClient(**production_config)
393
test_db = test_client.testdb
394
395
# Verify behavior with production-like settings
396
collection = test_db.users
397
result = collection.insert_one({'test': 'data'})
398
assert result.acknowledged
399
```
400
401
**Environment-Specific Configuration:**
402
403
```python
404
# Development settings
405
dev_config = CodecOptions(document_class=dict, tz_aware=False)
406
407
# Production settings
408
prod_config = CodecOptions(
409
document_class=OrderedDict,
410
tz_aware=True,
411
tzinfo=pytz.UTC
412
)
413
414
# Use appropriate config based on environment
415
config = prod_config if os.getenv('ENV') == 'production' else dev_config
416
client = mongomock.MongoClient()
417
db = client.get_database('myapp', codec_options=config)
418
```