MongoDB With Python
MongoDB With Python
By Arjun Panwar
Follow me on LinkedIn: https://www.linkedin.com/in/arjun-panwar/
Logging Class
In [1]:
from datetime import datetime # importing DateTime package
class App_Logger:
'''
It is used save logs into a file
Parameters
----------
file: log file name Default is logfile.log
'''
Parameters
----------
log_type: Type of log-info,error,warning etc
log_msg: Log to be saved(message)
'''
now = datetime.now() # current time
current_time = now.strftime("%d-%m-%Y %H:%M:%S") # changing time for
f = open(self.f_name, "a+") # opening file in append + mode
f.write(current_time + "," + log_type + "," + log_msg + "\n") # writ
f.close() # closing log file
In [ ]:
import pymongo
import pandas as pd
class mongodb:
'''
mongodb class through which we can perform most of the mongodb tasks usin
Parameters
----------
connection_url: connection url with password
db:db name
'''
Parameters
----------
COLLECTION_NAME: collection name
'''
try:
self.db[COLLECTION_NAME]
self.logger.log("info", f"{COLLECTION_NAME} collection created")
except Exception as e:
Parameters
----------
record: data to be inserted as dict, to insert many data use list of
'''
try:
if type(record)==dict:
collection = self.db[collection_name]
collection.insert_one(record)
elif type(record)==list:
collection = self.db[collection_name]
collection.insert_many(record)
self.logger.log("info", f"inserted successfully") # logging
except Exception as e:
Parameters
----------
collection_name: collection name
where_dict: condition as dict
new_dict:new values
'''
try:
collection = self.db[collection_name]
collection.update_many(where_dict,{"$set":new_dict} )
self.logger.log("info", f"update successfully") # logging
Parameters
----------
collection_name: collection name
where_dict: condition as dict
'''
try:
query_to_delete = where_dict
collection = self.db[collection_name]
collection.delete_one(query_to_delete)
self.logger.log("info", f"deleted successfully") # logging
except Exception as e:
self.logger.log("error", f"delete error : {str(e)}") # logging
def download(self,collection_name):
In [ ]:
url="" #mongodb connection URL
db="" #db Name
ob = mongodb(url,db)
Create Collection
In [ ]:
ob.create_collection(collection_name)
Insert in collection
In [ ]:
ob.insert(collection_name,record) #"record": for single record a dict,for man
Update in collection
In [ ]:
#set: "key=value pair of columns & values to be updated"
#where: "condition"
ob.update(collection_name,set, where)
Delete in collection
Download in collection
In [ ]:
ob.download(collection_name)
#it will return path to saved file