Created
December 10, 2018 18:16
-
-
Save oldarmyc/10052691980bae317a5e487a7e3af190 to your computer and use it in GitHub Desktop.
Mongo connection example
This file contains 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
""" | |
pymongo will need to be installed from conda for things to work properly | |
conda install -c anaconda pymongo | |
""" | |
import pymongo | |
import json | |
""" | |
Connect to the mongo server. In the example it is using the default auth mechanism | |
of SCRAM-SHA-256. You would need to change this if you are using different mechanism. | |
Some further authentication examples can be found here: | |
http://api.mongodb.com/python/current/examples/authentication.html | |
If you need to connect to a replica set you can see the examples here: | |
http://api.mongodb.com/python/current/examples/high_availability.html | |
""" | |
# Get credentials from kubernetes. The credentials were setup as a dictionary | |
credentials = None | |
with open('/var/run/secrets/user_credentials/mongo_credentials') as f: | |
credentials = json.load(f) | |
# Check and make sure the credentials were pulled correctly | |
if credentials: | |
# Connect to Mongo | |
client = pymongo.MongoClient( | |
'support-mongo.dev.anaconda.com', | |
username=credentials.get('username'), | |
password=credentials.get('password'), | |
authSource='test' | |
) | |
# Get the database you want to access | |
db = client.get_database('test') | |
# Query a collection for a single record and print it out | |
single_result = db.zipcodes.find_one() | |
print(json.dumps(single_result, indent=4)) | |
# Query a collection for multiple records and loop through them and print | |
multiple_results = db.zipcodes.find().limit(10) | |
for item in multiple_results: | |
print(json.dumps(item, indent=4)) | |
else: | |
# If credentials were not pulled properly print an error | |
print( | |
'Could not get credentials. Ensure that you setup your ' | |
'users credentials for this database server' | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment