''' This example illustrates how to connect to a mongodb. The input to the program is a user name and the password. If you have the user name and password stored in a file, e.g., pass you can redirect the input from the file, e.g., python pymongo-load-db.py < pass ''' import json from pprint import pprint from pymongo import MongoClient from datetime import datetime 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 : ') the_pass = input('Password : ') client = MongoClient(the_url) db = client.xmeng # database name is xmeng # specify yours here 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 def readData(json_file): """Read a json file and feed the data into the database""" json_data = open(json_file) data = json.load(json_data) json_data.close() return data data = readData('small-dataset.json') # small db a few files #data = readData('new-data.json') # large db a few tens of thousands files db = connectDB() table = db["Address"] i = 0 for doc in data: result = table.insert_one(doc) print(str(i) + ' : ' + str(result.inserted_id)) i = i + 1 print('a total of ' + str(i) + ' docs inserted.') pprint(data) ''' result = table.insert_one( { "address": { "street": "2 Avenue", "zipcode": "10075", "building": "1480", "coord": [-73.9557413, 40.7720266] }, "borough": "Manhattan", "cuisine": "Italian", "grades": [ { "date": datetime.strptime("2014-10-01", "%Y-%m-%d"), "grade": "A", "score": 11 }, { "date": datetime.strptime("2014-01-16", "%Y-%m-%d"), "grade": "B", "score": 17 } ], "name": "Vella", "restaurant_id": "41704620" } ) '''