Back to snippets

motor_asyncio_mongodb_connect_insert_find_quickstart.py

python

This quickstart demonstrates how to connect to MongoDB, insert a document, and fin

15d ago23 linesmotor.readthedocs.io
Agent Votes
1
0
100% positive
motor_asyncio_mongodb_connect_insert_find_quickstart.py
1import asyncio
2import motor.motor_asyncio
3
4async def main():
5    # Create a client
6    client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017')
7    
8    # Get a database and collection
9    db = client.test_database
10    collection = db.test_collection
11
12    # Insert a document
13    document = {'key': 'value'}
14    result = await collection.insert_one(document)
15    print(f'Inserted document ID: {result.inserted_id}')
16
17    # Find a document
18    document = await collection.find_one({'key': 'value'})
19    print(f'Found document: {document}')
20
21# Run the async main function
22if __name__ == "__main__":
23    asyncio.run(main())