Created
July 25, 2017 00:36
-
-
Save daveaseeman/c5982aac825749db6b1e06a98c3ed303 to your computer and use it in GitHub Desktop.
PyMongo Example - https://github.com/mongolab/mongodb-driver-examples/blob/master/python/pymongo_simple_example.py
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
#!/usr/bin/python | |
# Copyright (c) 2017 ObjectLabs Corporation | |
# Distributed under the MIT license - http://opensource.org/licenses/MIT | |
__author__ = 'mLab' | |
# Written with pymongo-3.4 | |
# Documentation: http://docs.mongodb.org/ecosystem/drivers/python/ | |
# A python script connecting to a MongoDB given a MongoDB Connection URI. | |
import sys | |
import pymongo | |
### Create seed data | |
SEED_DATA = [ | |
{ | |
'decade': '1970s', | |
'artist': 'Debby Boone', | |
'song': 'You Light Up My Life', | |
'weeksAtOne': 10 | |
}, | |
{ | |
'decade': '1980s', | |
'artist': 'Olivia Newton-John', | |
'song': 'Physical', | |
'weeksAtOne': 10 | |
}, | |
{ | |
'decade': '1990s', | |
'artist': 'Mariah Carey', | |
'song': 'One Sweet Day', | |
'weeksAtOne': 16 | |
} | |
] | |
### Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname | |
uri = 'mongodb://user:pass@host:port/db' | |
############################################################################### | |
# main | |
############################################################################### | |
def main(args): | |
client = pymongo.MongoClient(uri) | |
db = client.get_default_database() | |
# First we'll add a few songs. Nothing is required to create the songs | |
# collection; it is created automatically when we insert. | |
songs = db['songs'] | |
# Note that the insert method can take either an array or a single dict. | |
songs.insert_many(SEED_DATA) | |
# Then we need to give Boyz II Men credit for their contribution to | |
# the hit "One Sweet Day". | |
query = {'song': 'One Sweet Day'} | |
songs.update(query, {'$set': {'artist': 'Mariah Carey ft. Boyz II Men'}}) | |
# Finally we run a query which returns all the hits that spent 10 or | |
# more weeks at number 1. | |
cursor = songs.find({'weeksAtOne': {'$gte': 10}}).sort('decade', 1) | |
for doc in cursor: | |
print ('In the %s, %s by %s topped the charts for %d straight weeks.' % | |
(doc['decade'], doc['song'], doc['artist'], doc['weeksAtOne'])) | |
### Since this is an example, we'll clean up after ourselves. | |
db.drop_collection('songs') | |
### Only close the connection when your app is terminating | |
client.close() | |
if __name__ == '__main__': | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment