''' This is a basic Python program to allow a user of mongodb to login with her user name and password and perform some basic operations. Here are the steps. 1. Import the MongoClient package from pymongo as from pymongo import MongoClient 2. Connect to the mongodb server as client = MongoClient('mongodb://eg-mongodb.bucknell.edu') Note that the client connection doesn't contain user name or password. 3. Select the database to be used as db = client.[db-name] e.g., db = client.xmeng Note that here the database we connect to in the example is 'xmeng', one should choose a valid database. 4. Authenticate with proper user name and password as db.authenticate('user-name', 'password') The operation should return 'true' if succeeding, 'false' otherwise. ''' from pymongo import MongoClient from getpass import getpass import sys def connectDB(): """Connect to DB with given credentials Use input redict to avoid typing on the terminal directly""" the_url = 'mongodb://eg-mongodb.bucknell.edu' the_user = input('User name : ') # owner print('Password : ', end = '') # non-echo to read password the_pass = getpass() client = MongoClient(the_url) db = client.xmeng # database name is xmeng try: auth_result = db.authenticate(the_user, the_pass)# auth for this db only print('authentication result : ' + str(auth_result)) if (auth_result == True): return db else: return None except: print('Authentication problem') sys.exit(1) def testInsert(): """Inser a doc into the 'post' collection""" print('Insert a doc into the "post" collection ...') insrt_result = db.post.insert_one({"title":"fifth world", "by":"newcomer", "likes":28}) print(insrt_result) def printDocs(docs): """Print the entire 'docs' collection""" i = 0 for document in docs: print(str(i) + 'th doc : ', end = '') print(document) i = i + 1 print() print('a total of ' + str(i) + ' documents.') def printAll(db): """Retrieve and print the entire 'post' colletion""" ''' cursor = db.post.find() # query the 'post' collection # without criteria returns all docs print('----- Entire database ----- ') printDocs(cursor) ''' db.post.find().pretty() def testQuery(db): """Query by specified condition on a field (column)""" cursor = db.post.find({"likes":{"$gt":25}}) print('----- All documents that have more than 25 "likes" ----- ') printDocs(cursor) db = connectDB() #testInsert() printAll(db) #testQuery(db)