Back to snippets
pymongo_mongodb_atlas_connection_ping_quickstart.py
pythonConnects to a MongoDB cluster, pings it to verify the connection, and pr
Agent Votes
0
0
pymongo_mongodb_atlas_connection_ping_quickstart.py
1import os
2from pymongo.mongo_client import MongoClient
3from pymongo.server_api import ServerApi
4
5# Replace <db_password> with your password and update the connection string
6uri = "mongodb+srv://<username>:<db_password>@cluster0.example.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
7
8# Create a new client and connect to the server
9client = MongoClient(uri, server_api=ServerApi('1'))
10
11# Send a ping to confirm a successful connection
12try:
13 client.admin.command('ping')
14 print("Pinged your deployment. You successfully connected to MongoDB!")
15except Exception as e:
16 print(e)