Skip to content

MongoDB with Motor (Python asyncio)

Uses Motor 3.7. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.

mongodb://app:secret@mongo.example.com:27017/shop?authSource=admin
mongodb://app:secret@machnosql.example.com:27017/shop?authSource=admin

The address comes from the environment variable MONGODB_URI, so switching to MachNoSQL changes configuration only.

Terminal window
export MONGODB_URI='mongodb://app:secret@machnosql.example.com:27017/shop?authSource=admin'
pip install -r requirements.txt
python app.py

Motor is in maintenance mode; new code can use PyMongo’s AsyncMongoClient (from pymongo import AsyncMongoClient) with the same URI.

The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.

app.py
"""Orders example for MongoDB with asyncio, unchanged on MachNoSQL."""
import asyncio
import os
from motor.motor_asyncio import AsyncIOMotorClient
async def main() -> None:
client = AsyncIOMotorClient(os.environ["MONGODB_URI"])
orders = client.get_default_database()["orders"]
await orders.delete_many({})
await orders.insert_many(
[
{"customer": "ada", "item": "keyboard", "qty": 1, "price": 49.0},
{"customer": "ada", "item": "mouse", "qty": 2, "price": 19.5},
{"customer": "linus", "item": "monitor", "qty": 1, "price": 199.0},
]
)
print(await orders.find_one({"item": "mouse"}, {"_id": 0}))
await orders.update_one({"item": "mouse"}, {"$inc": {"qty": 1}})
pipeline = [
{"$group": {"_id": "$customer", "revenue": {"$sum": {"$multiply": ["$qty", "$price"]}}}},
{"$sort": {"revenue": -1}},
]
async for row in orders.aggregate(pipeline):
print(row)
asyncio.run(main())
requirements.txt
motor==3.7.1