-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupsert_operations.py
More file actions
41 lines (31 loc) · 1.16 KB
/
Copy pathupsert_operations.py
File metadata and controls
41 lines (31 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import asyncio
from datetime import datetime
import mongojet
import msgspec
import mongospec
from mongospec import IndexModel, MongoDocument
class User(MongoDocument):
__collection_name__ = "users"
__indexes__ = [IndexModel(keys=[("email", 1)], options={"unique": True})]
name: str
email: str
status: str = "inactive"
created_at: datetime = msgspec.field(default_factory=datetime.now)
async def main():
mongo_client = await mongojet.create_client("mongodb://localhost:27017")
await mongospec.init(mongo_client.get_database("example_db"), document_types=[User])
try:
# Save with upsert (insert if not exists, otherwise update)
user = User(name="Alice", email="alice@example.com", status="active")
await user.save(
upsert=True
) # this will insert Alice since she doesn't exist yet
# Update with upsert (will insert a new document if filter finds nothing)
await User.update_one(
{"email": "bob@example.com"},
{"$set": {"name": "Bob Smith", "status": "active"}},
upsert=True,
)
finally:
await mongospec.close()
asyncio.run(main())