0
# Database Engines
1
2
ODMantic provides both async and sync database engines for MongoDB operations. The AIOEngine is designed for async/await patterns with motor, while SyncEngine provides traditional synchronous operations with pymongo.
3
4
## Capabilities
5
6
### AIOEngine
7
8
Async MongoDB operations engine using the motor driver for high-performance async applications.
9
10
```python { .api }
11
class AIOEngine:
12
"""Asynchronous MongoDB engine using motor driver."""
13
14
def __init__(self, client=None, database="test"):
15
"""
16
Initialize async engine.
17
18
Args:
19
client: AsyncIOMotorClient instance, creates default if None
20
database: Database name to use (default: "test")
21
"""
22
23
def get_collection(self, model):
24
"""
25
Get motor collection for a model.
26
27
Args:
28
model: Model class
29
30
Returns:
31
AsyncIOMotorCollection: Motor collection object
32
"""
33
34
def session(self):
35
"""
36
Create new async session context manager.
37
38
Returns:
39
AIOSession: Session context manager
40
"""
41
42
def transaction(self):
43
"""
44
Create new async transaction context manager.
45
46
Returns:
47
AIOTransaction: Transaction context manager
48
"""
49
50
def find(self, model, *queries, sort=None, skip=0, limit=None, session=None):
51
"""
52
Find documents matching queries.
53
54
Args:
55
model: Model class to query
56
*queries: Query expressions to apply
57
sort: Sort expression or tuple of field proxies
58
skip: Number of documents to skip
59
limit: Maximum number of documents to return
60
session: Session for the operation
61
62
Returns:
63
AIOCursor: Async cursor for iteration
64
"""
65
66
async def find_one(self, model, *queries, sort=None, session=None):
67
"""
68
Find single document matching queries.
69
70
Args:
71
model: Model class to query
72
*queries: Query expressions to apply
73
sort: Sort expression or tuple of field proxies
74
session: Session for the operation
75
76
Returns:
77
Model instance or None if not found
78
"""
79
80
async def save(self, instance, *, session=None):
81
"""
82
Save model instance to database.
83
84
Args:
85
instance: Model instance to save
86
session: Session for the operation
87
88
Returns:
89
Model instance with updated fields
90
"""
91
92
async def save_all(self, instances, *, session=None):
93
"""
94
Save multiple model instances to database.
95
96
Args:
97
instances: List of model instances to save
98
session: Session for the operation
99
100
Returns:
101
List of model instances with updated fields
102
"""
103
104
async def delete(self, instance, *, session=None):
105
"""
106
Delete model instance from database.
107
108
Args:
109
instance: Model instance to delete
110
session: Session for the operation
111
"""
112
113
async def remove(self, model, *queries, just_one=False, session=None):
114
"""
115
Remove documents matching queries.
116
117
Args:
118
model: Model class to remove from
119
*queries: Query expressions to apply
120
just_one: Remove only the first matching document
121
session: Session for the operation
122
123
Returns:
124
int: Number of documents removed
125
"""
126
127
async def count(self, model, *queries, session=None):
128
"""
129
Count documents matching queries.
130
131
Args:
132
model: Model class to count
133
*queries: Query expressions to apply
134
session: Session for the operation
135
136
Returns:
137
int: Number of matching documents
138
"""
139
140
async def configure_database(self, models, session=None, update_existing_indexes=False):
141
"""
142
Configure database indexes for models.
143
144
Args:
145
models: List of model classes to configure
146
session: Session for the operation
147
update_existing_indexes: Update existing indexes if True
148
"""
149
```
150
151
### SyncEngine
152
153
Synchronous MongoDB operations engine using the pymongo driver for traditional sync applications.
154
155
```python { .api }
156
class SyncEngine:
157
"""Synchronous MongoDB engine using pymongo driver."""
158
159
def __init__(self, client=None, database="test"):
160
"""
161
Initialize sync engine.
162
163
Args:
164
client: MongoClient instance, creates default if None
165
database: Database name to use (default: "test")
166
"""
167
168
def get_collection(self, model):
169
"""
170
Get pymongo collection for a model.
171
172
Args:
173
model: Model class
174
175
Returns:
176
Collection: Pymongo collection object
177
"""
178
179
def session(self):
180
"""
181
Create new sync session context manager.
182
183
Returns:
184
SyncSession: Session context manager
185
"""
186
187
def transaction(self):
188
"""
189
Create new sync transaction context manager.
190
191
Returns:
192
SyncTransaction: Transaction context manager
193
"""
194
195
def find(self, model, *queries, sort=None, skip=0, limit=None, session=None):
196
"""
197
Find documents matching queries.
198
199
Args:
200
model: Model class to query
201
*queries: Query expressions to apply
202
sort: Sort expression or tuple of field proxies
203
skip: Number of documents to skip
204
limit: Maximum number of documents to return
205
session: Session for the operation
206
207
Returns:
208
SyncCursor: Sync cursor for iteration
209
"""
210
211
def find_one(self, model, *queries, sort=None, session=None):
212
"""
213
Find single document matching queries.
214
215
Args:
216
model: Model class to query
217
*queries: Query expressions to apply
218
sort: Sort expression or tuple of field proxies
219
session: Session for the operation
220
221
Returns:
222
Model instance or None if not found
223
"""
224
225
def save(self, instance, *, session=None):
226
"""
227
Save model instance to database.
228
229
Args:
230
instance: Model instance to save
231
session: Session for the operation
232
233
Returns:
234
Model instance with updated fields
235
"""
236
237
def save_all(self, instances, *, session=None):
238
"""
239
Save multiple model instances to database.
240
241
Args:
242
instances: List of model instances to save
243
session: Session for the operation
244
245
Returns:
246
List of model instances with updated fields
247
"""
248
249
def delete(self, instance, *, session=None):
250
"""
251
Delete model instance from database.
252
253
Args:
254
instance: Model instance to delete
255
session: Session for the operation
256
"""
257
258
def remove(self, model, *queries, just_one=False, session=None):
259
"""
260
Remove documents matching queries.
261
262
Args:
263
model: Model class to remove from
264
*queries: Query expressions to apply
265
just_one: Remove only the first matching document
266
session: Session for the operation
267
268
Returns:
269
int: Number of documents removed
270
"""
271
272
def count(self, model, *queries, session=None):
273
"""
274
Count documents matching queries.
275
276
Args:
277
model: Model class to count
278
*queries: Query expressions to apply
279
session: Session for the operation
280
281
Returns:
282
int: Number of matching documents
283
"""
284
285
def configure_database(self, models, session=None, update_existing_indexes=False):
286
"""
287
Configure database indexes for models.
288
289
Args:
290
models: List of model classes to configure
291
session: Session for the operation
292
update_existing_indexes: Update existing indexes if True
293
"""
294
```
295
296
### Cursor Objects
297
298
Cursors provide iteration over query results with different async/sync patterns.
299
300
```python { .api }
301
class AIOCursor:
302
"""Async cursor supporting both async iteration and await."""
303
304
def __aiter__(self):
305
"""Async iterator protocol."""
306
307
def __await__(self):
308
"""Await to get list of all results."""
309
310
class SyncCursor:
311
"""Sync cursor supporting regular iteration."""
312
313
def __iter__(self):
314
"""Iterator protocol."""
315
```
316
317
## Usage Examples
318
319
### Basic Async Operations
320
321
```python
322
from odmantic import AIOEngine, Model
323
from motor.motor_asyncio import AsyncIOMotorClient
324
import asyncio
325
326
class User(Model):
327
name: str
328
email: str
329
330
async def example():
331
client = AsyncIOMotorClient("mongodb://localhost:27017")
332
engine = AIOEngine(client, database="mydb")
333
334
# Save a user
335
user = User(name="Alice", email="alice@example.com")
336
await engine.save(user)
337
338
# Find users
339
cursor = engine.find(User, User.name == "Alice")
340
async for user in cursor:
341
print(user.name)
342
343
# Or get all at once
344
users = await engine.find(User, User.name == "Alice")
345
print(f"Found {len(users)} users")
346
347
asyncio.run(example())
348
```
349
350
### Basic Sync Operations
351
352
```python
353
from odmantic import SyncEngine, Model
354
from pymongo import MongoClient
355
356
class User(Model):
357
name: str
358
email: str
359
360
client = MongoClient("mongodb://localhost:27017")
361
engine = SyncEngine(client, database="mydb")
362
363
# Save a user
364
user = User(name="Bob", email="bob@example.com")
365
engine.save(user)
366
367
# Find users
368
cursor = engine.find(User, User.name == "Bob")
369
for user in cursor:
370
print(user.name)
371
372
# Count users
373
count = engine.count(User, User.name == "Bob")
374
print(f"Found {count} users")
375
```
376
377
### Session Usage
378
379
```python
380
# Async session
381
async with engine.session() as session:
382
user = User(name="Charlie", email="charlie@example.com")
383
await engine.save(user, session=session)
384
users = await engine.find(User, session=session)
385
386
# Sync session
387
with engine.session() as session:
388
user = User(name="Dave", email="dave@example.com")
389
engine.save(user, session=session)
390
users = list(engine.find(User, session=session))
391
```