Sample code of pymongo to connect with MongoDB.
https://pymongo.readthedocs.io/en/stable/index.html#
https://www.w3schools.com/python/python_mongodb_getstarted.asp
# conda env py36db
# !python -m pip install pymongo
import pymongo
Important: In MongoDB, a database is not created until it gets content!
import datetime
client = pymongo.MongoClient('localhost', 27017)
db = client["mydatabase"]
collection = db["customers"]
dict = { "name": "John", "address": "Highway 37"}
dicts = collection.insert_one(dict)
print(client.list_database_names())
dblist = client.list_database_names()
if "mydatabase" in dblist:
print("The database exists.")
print(db.list_collection_names())
collist = db.list_collection_names()
if "customers" in collist:
print("The collection exists.")
print(dicts.inserted_id)
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["customers"]
new_list = [
{ "name": "Amy", "address": "Apple st 652"},
{ "name": "Hannah", "address": "Mountain 21"},
{ "name": "Michael", "address": "Valley 345"},
{ "name": "Sandy", "address": "Ocean blvd 2"},
{ "name": "Betty", "address": "Green Grass 1"},
{ "name": "Richard", "address": "Sky st 331"},
{ "name": "Susan", "address": "One way 98"},
{ "name": "Vicky", "address": "Yellow Garden 2"},
{ "name": "Ben", "address": "Park Lane 38"},
{ "name": "William", "address": "Central st 954"},
{ "name": "Chuck", "address": "Main Road 989"},
{ "name": "Viola", "address": "Sideway 1633"}
]
insert_list = collection.insert_many(new_list)
#print list of the _id values of the inserted documents:
print(insert_list.inserted_ids)
new_list = [
{ "_id": 1, "name": "John", "address": "Highway 37"},
{ "_id": 2, "name": "Peter", "address": "Lowstreet 27"},
{ "_id": 3, "name": "Amy", "address": "Apple st 652"},
{ "_id": 4, "name": "Hannah", "address": "Mountain 21"},
{ "_id": 5, "name": "Michael", "address": "Valley 345"},
{ "_id": 6, "name": "Sandy", "address": "Ocean blvd 2"},
{ "_id": 7, "name": "Betty", "address": "Green Grass 1"},
{ "_id": 8, "name": "Richard", "address": "Sky st 331"},
{ "_id": 9, "name": "Susan", "address": "One way 98"},
{ "_id": 10, "name": "Vicky", "address": "Yellow Garden 2"},
{ "_id": 11, "name": "Ben", "address": "Park Lane 38"},
{ "_id": 12, "name": "William", "address": "Central st 954"},
{ "_id": 13, "name": "Chuck", "address": "Main Road 989"},
{ "_id": 14, "name": "Viola", "address": "Sideway 1633"}
]
insert_list = collection.insert_many(new_list)
#print list of the _id values of the inserted documents:
print(insert_list.inserted_ids)
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["customers"]
find_doc = collection.find_one()
print(find_doc)
for x in collection.find():
print(x)
for x in collection.find({},{ "_id": 0, "name": 1, "address": 1 }):
print(x)
for x in collection.find({"name": "Betty"}):
print(x)
import pprint
pprint.pprint(collection.find_one())
pprint.pprint(collection.find_one({"name": "Betty"}))
query = { "address": "Park Lane 38" }
doc = collection.find(query)
for x in doc:
print(x)
# Find documents where the address starts with the letter "S" or higher:
query = { "address": { "$gt": "S" } }
doc = collection.find(query)
for x in doc:
print(x)
query = { "address": { "$regex": "^S" } }
doc = collection.find(query)
for x in doc:
print(x)
# ascending
doc = collection.find().sort("name")
for x in doc:
print(x)
# descending
doc = collection.find().sort("name", -1)
for x in doc:
print(x)
collection = db["customers"]
query = { "address": "Mountain 21" }
collection.delete_one(query)
collection = db["customers"]
query = { "address": {"$regex": "^S"} }
x = collection.delete_many(query)
print(x.deleted_count, " documents deleted.")
db = client["mydatabase"]
collection = db["customers"]
collection.drop()
query = { "address": "Valley 345" }
newvalues = { "$set": { "address": "Canyon 123" } }
collection.update_one(query, newvalues)
#print "customers" after the update:
for x in collection.find():
print(x)
doc = collection.find().limit(5)
#print the result:
for x in doc:
print(x)
collection.count_documents({})
import pandas as pd
query = { "address": "Park Lane 38" }
doc = collection.find(query)
df = pd.DataFrame(list(doc))
df
import pandas as pd
from pymongo import MongoClient
def mongo_connection(host, port, username, password, db):
""" Create connection to mongo """
if username and password:
mongo_uri = 'mongodb://%s:%s@%s:%s/%s' % (username, password, host, port, db)
connection = client(mongo_uri)
else:
connection = client(host, port)
return connection[db]
def read_mongo(db, collection, query={}, host='localhost', port=27017, username=None, password=None, no_id=True):
""" Read from Mongo and Store into DataFrame """
# Connect to MongoDB
db = mongo_connection(host=host, port=port, username=username, password=password, db=db)
# Make a query to the specific DB and Collection
cursor = db[collection].find(query)
# Expand the cursor and construct the DataFrame
df = pd.DataFrame(list(cursor))
# Delete the _id
if no_id:
del df['_id']
return df
# if __name__ == '__main__':
# mongo_connection()
# df = read_mongo()