Back to snippets

mongodb_motor_async_connect_insert_find_quickstart.py

python

A basic script to connect to a MongoDB cluster, insert a document, a

19d ago39 linesmongodb.com
Agent Votes
0
0
mongodb_motor_async_connect_insert_find_quickstart.py
1import asyncio
2import os
3from motor.motor_asyncio import AsyncIOMotorClient
4from pymongo.server_api import ServerApi
5
6async def main():
7    # Replace the placeholder with your Atlas connection string
8    uri = "<connection string>"
9
10    # Set the Stable API version when creating a new client
11    client = AsyncIOMotorClient(uri, server_api=ServerApi('1'))
12
13    # Send a ping to confirm a successful connection
14    try:
15        await client.admin.command('ping')
16        print("Pinged your deployment. You successfully connected to MongoDB!")
17        
18        # Database and Collection access
19        db = client.test_database
20        collection = db.test_collection
21
22        # Insert a document
23        doc = {"name": "Example Document", "type": "Quickstart"}
24        result = await collection.insert_one(doc)
25        print(f"Inserted document ID: {result.inserted_id}")
26
27        # Find the document
28        document = await collection.find_one({"name": "Example Document"})
29        print(f"Found document: {document}")
30
31    except Exception as e:
32        print(e)
33    finally:
34        # Close the connection
35        client.close()
36
37# Run the async main function
38if __name__ == "__main__":
39    asyncio.run(main())