0
# Collection CRUD Operations
1
2
Complete Create, Read, Update, Delete operations with support for bulk operations, complex queries, and MongoDB-compatible filtering and sorting. The Collection class provides the primary interface for document manipulation.
3
4
## Capabilities
5
6
### Document Insertion
7
8
Insert single or multiple documents into collections with support for validation bypass and bulk operations.
9
10
```python { .api }
11
def insert_one(self, document, bypass_document_validation=False, session=None):
12
"""
13
Insert a single document.
14
15
Parameters:
16
- document: dict, document to insert
17
- bypass_document_validation: bool, skip document validation
18
- session: ClientSession, session to use (ignored)
19
20
Returns:
21
InsertOneResult: result with inserted_id and acknowledged status
22
23
Raises:
24
DuplicateKeyError: if duplicate key constraint violated
25
WriteError: if write operation fails
26
"""
27
28
def insert_many(self, documents, ordered=True,
29
bypass_document_validation=False, session=None):
30
"""
31
Insert multiple documents.
32
33
Parameters:
34
- documents: list of dict, documents to insert
35
- ordered: bool, stop on first error if True
36
- bypass_document_validation: bool, skip document validation
37
- session: ClientSession, session to use (ignored)
38
39
Returns:
40
InsertManyResult: result with inserted_ids and acknowledged status
41
42
Raises:
43
BulkWriteError: if bulk operation fails
44
DuplicateKeyError: if duplicate key constraint violated
45
"""
46
```
47
48
**Usage Example:**
49
50
```python
51
collection = mongomock.MongoClient().db.users
52
53
# Insert single document
54
result = collection.insert_one({
55
'name': 'Alice',
56
'email': 'alice@example.com',
57
'age': 30
58
})
59
print(f"Inserted ID: {result.inserted_id}")
60
61
# Insert multiple documents
62
users = [
63
{'name': 'Bob', 'age': 25},
64
{'name': 'Charlie', 'age': 35},
65
{'name': 'David', 'age': 28}
66
]
67
result = collection.insert_many(users)
68
print(f"Inserted {len(result.inserted_ids)} documents")
69
```
70
71
### Document Querying
72
73
Find documents using MongoDB query syntax with support for projection, sorting, limiting, and cursor operations.
74
75
```python { .api }
76
def find(self, filter=None, projection=None, skip=0, limit=0,
77
sort=None, cursor_type=None, collation=None, hint=None,
78
session=None, **kwargs):
79
"""
80
Find documents matching filter criteria.
81
82
Parameters:
83
- filter: dict, query filter (None matches all)
84
- projection: dict or list, fields to include/exclude
85
- skip: int, number of documents to skip
86
- limit: int, maximum number of documents to return
87
- sort: list of (key, direction) tuples or dict
88
- cursor_type: CursorType, cursor type (ignored)
89
- collation: dict, collation specification (limited support)
90
- hint: str or list, index hint
91
- session: ClientSession, session to use (ignored)
92
- **kwargs: additional query options
93
94
Returns:
95
Cursor: cursor over matching documents
96
"""
97
98
def find_one(self, filter=None, *args, **kwargs):
99
"""
100
Find a single document.
101
102
Parameters:
103
- filter: dict, query filter (None matches any)
104
- *args, **kwargs: same as find()
105
106
Returns:
107
dict or None: matching document or None if not found
108
"""
109
```
110
111
**Usage Example:**
112
113
```python
114
collection = mongomock.MongoClient().db.users
115
116
# Find all documents
117
all_users = list(collection.find())
118
119
# Find with filter
120
young_users = list(collection.find({'age': {'$lt': 30}}))
121
122
# Find with projection
123
names_only = list(collection.find({}, {'name': 1, '_id': 0}))
124
125
# Find with sorting and limiting
126
top_users = list(collection.find().sort('age', -1).limit(5))
127
128
# Find one document
129
user = collection.find_one({'name': 'Alice'})
130
131
# Complex query
132
adults = list(collection.find({
133
'age': {'$gte': 18, '$lt': 65},
134
'status': {'$in': ['active', 'pending']}
135
}))
136
```
137
138
### Find and Modify Operations
139
140
Atomic find-and-modify operations that combine query and modification in single operations.
141
142
```python { .api }
143
def find_one_and_delete(self, filter, projection=None, sort=None, **kwargs):
144
"""
145
Find a document and delete it atomically.
146
147
Parameters:
148
- filter: dict, query filter
149
- projection: dict or list, fields to return
150
- sort: list of (key, direction) tuples
151
- **kwargs: additional options
152
153
Returns:
154
dict or None: deleted document or None if not found
155
"""
156
157
def find_one_and_replace(self, filter, replacement, projection=None,
158
sort=None, upsert=False,
159
return_document=ReturnDocument.BEFORE, **kwargs):
160
"""
161
Find a document and replace it atomically.
162
163
Parameters:
164
- filter: dict, query filter
165
- replacement: dict, replacement document
166
- projection: dict or list, fields to return
167
- sort: list of (key, direction) tuples
168
- upsert: bool, insert if no match found
169
- return_document: ReturnDocument.BEFORE or AFTER
170
- **kwargs: additional options
171
172
Returns:
173
dict or None: original or modified document
174
"""
175
176
def find_one_and_update(self, filter, update, projection=None, sort=None,
177
upsert=False, return_document=ReturnDocument.BEFORE,
178
**kwargs):
179
"""
180
Find a document and update it atomically.
181
182
Parameters:
183
- filter: dict, query filter
184
- update: dict, update operations
185
- projection: dict or list, fields to return
186
- sort: list of (key, direction) tuples
187
- upsert: bool, insert if no match found
188
- return_document: ReturnDocument.BEFORE or AFTER
189
- **kwargs: additional options
190
191
Returns:
192
dict or None: original or modified document
193
"""
194
```
195
196
**Usage Example:**
197
198
```python
199
from mongomock import ReturnDocument
200
201
collection = mongomock.MongoClient().db.users
202
203
# Find and delete
204
deleted_user = collection.find_one_and_delete({'name': 'Bob'})
205
206
# Find and replace
207
new_user = collection.find_one_and_replace(
208
{'name': 'Alice'},
209
{'name': 'Alice Smith', 'age': 31, 'email': 'alice.smith@example.com'},
210
return_document=ReturnDocument.AFTER
211
)
212
213
# Find and update
214
updated_user = collection.find_one_and_update(
215
{'name': 'Charlie'},
216
{'$set': {'age': 36}, '$inc': {'login_count': 1}},
217
return_document=ReturnDocument.AFTER
218
)
219
```
220
221
### Document Updates
222
223
Update documents using MongoDB update operators with support for single and multiple document updates.
224
225
```python { .api }
226
def update_one(self, filter, update, upsert=False,
227
bypass_document_validation=False, collation=None,
228
array_filters=None, hint=None, session=None):
229
"""
230
Update a single document.
231
232
Parameters:
233
- filter: dict, query filter
234
- update: dict, update operations
235
- upsert: bool, insert if no match found
236
- bypass_document_validation: bool, skip validation
237
- collation: dict, collation specification (limited support)
238
- array_filters: list, array element filters
239
- hint: str or list, index hint
240
- session: ClientSession, session to use (ignored)
241
242
Returns:
243
UpdateResult: result with match/modification counts
244
245
Raises:
246
WriteError: if update operation fails
247
"""
248
249
def update_many(self, filter, update, upsert=False,
250
bypass_document_validation=False, collation=None,
251
array_filters=None, hint=None, session=None):
252
"""
253
Update multiple documents.
254
255
Parameters:
256
- filter: dict, query filter
257
- update: dict, update operations
258
- upsert: bool, insert if no match found
259
- bypass_document_validation: bool, skip validation
260
- collation: dict, collation specification (limited support)
261
- array_filters: list, array element filters
262
- hint: str or list, index hint
263
- session: ClientSession, session to use (ignored)
264
265
Returns:
266
UpdateResult: result with match/modification counts
267
268
Raises:
269
WriteError: if update operation fails
270
"""
271
272
def replace_one(self, filter, replacement, upsert=False,
273
bypass_document_validation=False, collation=None,
274
hint=None, session=None):
275
"""
276
Replace a single document.
277
278
Parameters:
279
- filter: dict, query filter
280
- replacement: dict, replacement document
281
- upsert: bool, insert if no match found
282
- bypass_document_validation: bool, skip validation
283
- collation: dict, collation specification (limited support)
284
- hint: str or list, index hint
285
- session: ClientSession, session to use (ignored)
286
287
Returns:
288
UpdateResult: result with match/modification counts
289
290
Raises:
291
WriteError: if replace operation fails
292
"""
293
```
294
295
**Usage Example:**
296
297
```python
298
collection = mongomock.MongoClient().db.users
299
300
# Update single document
301
result = collection.update_one(
302
{'name': 'Alice'},
303
{'$set': {'age': 31}, '$inc': {'login_count': 1}}
304
)
305
print(f"Modified: {result.modified_count}")
306
307
# Update multiple documents
308
result = collection.update_many(
309
{'age': {'$lt': 30}},
310
{'$set': {'category': 'young'}}
311
)
312
print(f"Modified: {result.modified_count}")
313
314
# Replace document
315
result = collection.replace_one(
316
{'name': 'Bob'},
317
{'name': 'Robert', 'age': 26, 'email': 'robert@example.com'}
318
)
319
320
# Upsert (update or insert)
321
result = collection.update_one(
322
{'name': 'Eve'},
323
{'$set': {'age': 25}},
324
upsert=True
325
)
326
if result.upserted_id:
327
print(f"Inserted new document: {result.upserted_id}")
328
```
329
330
### Document Deletion
331
332
Remove documents from collections with support for single and multiple document deletion.
333
334
```python { .api }
335
def delete_one(self, filter, collation=None, hint=None, session=None):
336
"""
337
Delete a single document.
338
339
Parameters:
340
- filter: dict, query filter
341
- collation: dict, collation specification (limited support)
342
- hint: str or list, index hint
343
- session: ClientSession, session to use (ignored)
344
345
Returns:
346
DeleteResult: result with deletion count
347
348
Raises:
349
WriteError: if delete operation fails
350
"""
351
352
def delete_many(self, filter, collation=None, hint=None, session=None):
353
"""
354
Delete multiple documents.
355
356
Parameters:
357
- filter: dict, query filter
358
- collation: dict, collation specification (limited support)
359
- hint: str or list, index hint
360
- session: ClientSession, session to use (ignored)
361
362
Returns:
363
DeleteResult: result with deletion count
364
365
Raises:
366
WriteError: if delete operation fails
367
"""
368
```
369
370
**Usage Example:**
371
372
```python
373
collection = mongomock.MongoClient().db.users
374
375
# Delete single document
376
result = collection.delete_one({'name': 'Alice'})
377
print(f"Deleted: {result.deleted_count}")
378
379
# Delete multiple documents
380
result = collection.delete_many({'age': {'$gt': 65}})
381
print(f"Deleted: {result.deleted_count}")
382
383
# Delete all documents
384
result = collection.delete_many({})
385
print(f"Deleted all {result.deleted_count} documents")
386
```
387
388
### Document Counting
389
390
Count documents in collections with support for filtering and estimation.
391
392
```python { .api }
393
def count_documents(self, filter, **kwargs):
394
"""
395
Count documents matching filter.
396
397
Parameters:
398
- filter: dict, query filter
399
- **kwargs: additional count options
400
401
Returns:
402
int: number of matching documents
403
"""
404
405
def estimated_document_count(self, **kwargs):
406
"""
407
Estimate total document count in collection.
408
409
Parameters:
410
- **kwargs: additional options (ignored)
411
412
Returns:
413
int: estimated document count
414
"""
415
```
416
417
**Usage Example:**
418
419
```python
420
collection = mongomock.MongoClient().db.users
421
422
# Count with filter
423
young_count = collection.count_documents({'age': {'$lt': 30}})
424
print(f"Young users: {young_count}")
425
426
# Count all documents
427
total_count = collection.count_documents({})
428
429
# Estimated count (same as exact count in mongomock)
430
estimated = collection.estimated_document_count()
431
```
432
433
## Collection Constructor
434
435
```python { .api }
436
class Collection:
437
def __init__(self, database, name, create=False, **kwargs):
438
"""
439
Create a Collection instance.
440
441
Note: Collections are typically created via Database.get_collection()
442
rather than direct instantiation.
443
444
Parameters:
445
- database: Database, parent database instance
446
- name: str, collection name
447
- create: bool, explicitly create collection
448
- **kwargs: collection options
449
"""
450
```