0
# Bulk Operations
1
2
Efficient bulk write operations with transaction support for high-performance batch processing of multiple document operations.
3
4
## Capabilities
5
6
### BulkWriter
7
8
Context manager for efficient bulk write operations with automatic transaction handling.
9
10
```python { .api }
11
class BulkWriter:
12
"""Efficient bulk write operations handler with transaction support."""
13
14
def __init__(
15
self,
16
session: Optional[AsyncClientSession] = None,
17
ordered: bool = True,
18
object_class: Optional[Type[Union[Document, UnionDoc]]] = None,
19
bypass_document_validation: Optional[bool] = False,
20
comment: Optional[Any] = None,
21
) -> None:
22
"""Initialize bulk writer with optional session and configuration."""
23
...
24
25
async def __aenter__(self) -> "BulkWriter":
26
"""Enter context manager."""
27
...
28
29
async def __aexit__(self, exc_type, exc_val, exc_tb):
30
"""Exit context manager and commit operations."""
31
...
32
33
def add_operation(self, operation: Dict[str, Any]) -> None:
34
"""Queue a bulk operation for execution."""
35
...
36
37
async def commit(self) -> Any:
38
"""Execute all queued operations."""
39
...
40
```
41
42
## Usage Examples
43
44
```python
45
from beanie import Document, BulkWriter
46
from pymongo.asynchronous.client_session import AsyncClientSession
47
from typing import Optional, Type, Union, Any
48
49
class User(Document):
50
name: str
51
email: str
52
53
class Settings:
54
collection = "users"
55
56
# Basic bulk operations
57
async def bulk_insert_users():
58
users_data = [
59
{"name": "Alice", "email": "alice@example.com"},
60
{"name": "Bob", "email": "bob@example.com"},
61
{"name": "Charlie", "email": "charlie@example.com"}
62
]
63
64
async with BulkWriter() as bulk:
65
for user_data in users_data:
66
user = User(**user_data)
67
bulk.add_operation({"insert_one": user})
68
69
print("Bulk insert completed")
70
71
# Mixed operations
72
async def bulk_mixed_operations():
73
async with BulkWriter() as bulk:
74
# Insert new user
75
new_user = User(name="David", email="david@example.com")
76
bulk.add_operation({"insert_one": new_user})
77
78
# Update existing user
79
bulk.add_operation({
80
"update_one": {
81
"filter": {"email": "alice@example.com"},
82
"update": {"$set": {"name": "Alice Smith"}}
83
}
84
})
85
86
# Delete user
87
bulk.add_operation({
88
"delete_one": {
89
"filter": {"email": "charlie@example.com"}
90
}
91
})
92
```