Motor

Motor is an asyncio driver for MongoDB databases in Python.

Note

This package assumes you already know how to create a Mongo database and connect to it with Python3 IDE. If you don't know how to do this, follow the "Setting Up Your Database" section of the PyMongo documentation.

Warning

When including private database credentials in your code, make sure you DO NOT make your project "Open Source" when you share it.

Examples

Using the asyncio Client

Since motor is an async package, we need to perform database operations in async functions. Let's make a simple function that inserts 50 documents into a collection in our database:

Make sure you replace the mongodb server url with the one from your cloud MongoDB.

import asyncio
import motor.motor_asyncio

client = motor.motor_asyncio.AsyncIOMotorClient("mongodb+srv://testuser:<password>@<your cluster>.mongodb.net/?retryWrites=true&w=majority")
db = client.test_database

async def do_insert():
    result = await db.test_collection.insert_many(
        [{'i': i} for i in range(50)]
    )
    print(f'inserted {len(result.inserted_ids)} docs')

loop = client.get_io_loop()
loop.run_until_complete(do_insert())

We run it and will get the output:

inserted 50 docs

If we check out Mongo Atlas, we will see a list of all the documents we inserted to confirm the operation succeeded:

Reference

  • Motor at readthedocs.io