Created
May 15, 2022 06:23
-
-
Save ianychoi/0e80f3afa63fc3d85df328e98ab63705 to your computer and use it in GitHub Desktop.
MongoDB - Sample MongoDB connection test with Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
## Sample MongoDB connection test | |
## Source code from: https://github.com/Azure-Samples/azure-cosmos-db-mongodb-python-getting-started | |
## Recommended ways to execute this sample (assuming on Linux with Python 3) | |
## $ python3 -m venv .venv | |
## $ source .venv/bin/activate | |
## $ pip install pymongo | |
## $ python mongodb-connection-test.py | |
import getpass | |
import pprint | |
import pymongo | |
CONNECTION_STRING = getpass.getpass(prompt='Enter your primary connection string: ') # Prompts user for connection string | |
def main(): | |
"""Connect to the API for MongoDB, create DB and collection, perform CRUD operations""" | |
client = pymongo.MongoClient(CONNECTION_STRING) | |
try: | |
client.server_info() # validate connection string | |
except pymongo.errors.ServerSelectionTimeoutError: | |
raise TimeoutError("Invalid API for MongoDB connection string or timed out when attempting to connect") | |
server_info = client.server_info() | |
pprint.pprint(server_info) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment