-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongoDBOperations.py
348 lines (322 loc) · 14 KB
/
mongoDBOperations.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import pymongo
import pandas as pd
import json
class MongoDBManagement:
def __init__(self, username, password):
"""
This function sets the required url
"""
try:
self.username = username
self.password = password
self.url = "mongodb+srv://deepak2310:[email protected]/?retryWrites=true&w=majority".format(
self.username, self.password)
# self.url = 'localhost:27017'
except Exception as e:
raise Exception(f"(__init__): Something went wrong on initiation process\n" + str(e))
def getMongoDBClientObject(self):
"""
This function creates the client object for connection purpose
"""
try:
mongo_client = pymongo.MongoClient(self.url)
return mongo_client
except Exception as e:
raise Exception("(getMongoDBClientObject): Something went wrong on creation of client object\n" + str(e))
def closeMongoDBconnection(self, mongo_client):
"""
This function closes the connection of client
:return:
"""
try:
mongo_client.close()
except Exception as e:
raise Exception(f"Something went wrong on closing connection\n" + str(e))
def isDatabasePresent(self, db_name):
"""
This function checks if the database is present or not.
:param db_name:
:return:
"""
try:
mongo_client = self.getMongoDBClientObject()
if db_name in mongo_client.list_database_names():
mongo_client.close()
return True
else:
mongo_client.close()
return False
except Exception as e:
raise Exception("(isDatabasePresent): Failed on checking if the database is present or not \n" + str(e))
def createDatabase(self, db_name):
"""
This function creates database.
:param db_name:
:return:
"""
try:
database_check_status = self.isDatabasePresent(db_name=db_name)
if not database_check_status:
mongo_client = self.getMongoDBClientObject()
database = mongo_client[db_name]
mongo_client.close()
return database
else:
mongo_client = self.getMongoDBClientObject()
database = mongo_client[db_name]
mongo_client.close()
return database
except Exception as e:
raise Exception(f"(createDatabase): Failed on creating database\n" + str(e))
def dropDatabase(self, db_name):
"""
This function deletes the database from MongoDB
:param db_name:
:return:
"""
try:
mongo_client = self.getMongoDBClientObject()
if db_name in mongo_client.list_database_names():
mongo_client.drop_database(db_name)
mongo_client.close()
return True
except Exception as e:
raise Exception(f"(dropDatabase): Failed to delete database {db_name}\n" + str(e))
def getDatabase(self, db_name):
"""
This returns databases.
"""
try:
mongo_client = self.getMongoDBClientObject()
mongo_client.close()
return mongo_client[db_name]
except Exception as e:
raise Exception(f"(getDatabase): Failed to get the database list")
def getCollection(self, collection_name, db_name):
"""
This returns collection.
:return:
"""
try:
database = self.getDatabase(db_name)
return database[collection_name]
except Exception as e:
raise Exception(f"(getCollection): Failed to get the database list.")
def isCollectionPresent(self, collection_name, db_name):
"""
This checks if collection is present or not.
:param collection_name:
:param db_name:
:return:
"""
try:
database_status = self.isDatabasePresent(db_name=db_name)
if database_status:
database = self.getDatabase(db_name=db_name)
if collection_name in database.list_collection_names():
return True
else:
return False
else:
return False
except Exception as e:
raise Exception(f"(isCollectionPresent): Failed to check collection\n" + str(e))
def createCollection(self, collection_name, db_name):
"""
This function creates the collection in the database given.
:param collection_name:
:param db_name:
:return:
"""
try:
collection_check_status = self.isCollectionPresent(collection_name=collection_name, db_name=db_name)
if not collection_check_status:
database = self.getDatabase(db_name=db_name)
collection = database[collection_name]
return collection
except Exception as e:
raise Exception(f"(createCollection): Failed to create collection {collection_name}\n" + str(e))
def dropCollection(self, collection_name, db_name):
"""
This function drops the collection
:param collection_name:
:param db_name:
:return:
"""
try:
collection_check_status = self.isCollectionPresent(collection_name=collection_name, db_name=db_name)
if collection_check_status:
collection = self.getCollection(collection_name=collection_name, db_name=db_name)
collection.drop()
return True
else:
return False
except Exception as e:
raise Exception(f"(dropCollection): Failed to drop collection {collection_name}")
def insertRecord(self, db_name, collection_name, record):
"""
This inserts a record.
:param db_name:
:param collection_name:
:param record:
:return:
"""
try:
# collection_check_status = self.isCollectionPresent(collection_name=collection_name,db_name=db_name)
# print(collection_check_status)
# if collection_check_status:
collection = self.getCollection(collection_name=collection_name, db_name=db_name)
collection.insert_one(record)
sum = 0
return f"rows inserted "
except Exception as e:
raise Exception(f"(insertRecord): Something went wrong on inserting record\n" + str(e))
def insertRecords(self, db_name, collection_name, records):
"""
This inserts a record.
:param db_name:
:param collection_name:
:param record:
:return:
"""
try:
# collection_check_status = self.isCollectionPresent(collection_name=collection_name,db_name=db_name)
# print(collection_check_status)
# if collection_check_status:
collection = self.getCollection(collection_name=collection_name, db_name=db_name)
record = list(records.values())
collection.insert_many(record)
sum = 0
return f"rows inserted "
except Exception as e:
raise Exception(f"(insertRecords): Something went wrong on inserting record\n" + str(e))
def findfirstRecord(self, db_name, collection_name,query=None):
"""
"""
try:
collection_check_status = self.isCollectionPresent(collection_name=collection_name, db_name=db_name)
print(collection_check_status)
if collection_check_status:
collection = self.getCollection(collection_name=collection_name, db_name=db_name)
print(collection)
firstRecord = collection.find_one(query)
return firstRecord
except Exception as e:
raise Exception(f"(findRecord): Failed to find record for the given collection and database\n" + str(e))
def findAllRecords(self, db_name, collection_name):
"""
"""
try:
collection_check_status = self.isCollectionPresent(collection_name=collection_name, db_name=db_name)
if collection_check_status:
collection = self.getCollection(collection_name=collection_name, db_name=db_name)
findAllRecords = collection.find()
return findAllRecords
except Exception as e:
raise Exception(f"(findAllRecords): Failed to find record for the given collection and database\n" + str(e))
def findRecordOnQuery(self, db_name, collection_name, query):
"""
"""
try:
collection_check_status = self.isCollectionPresent(collection_name=collection_name, db_name=db_name)
if collection_check_status:
collection = self.getCollection(collection_name=collection_name, db_name=db_name)
findRecords = collection.find(query)
return findRecords
except Exception as e:
raise Exception(
f"(findRecordOnQuery): Failed to find record for given query,collection or database\n" + str(e))
def updateOneRecord(self, db_name, collection_name, query):
"""
"""
try:
collection_check_status = self.isCollectionPresent(collection_name=collection_name, db_name=db_name)
if collection_check_status:
collection = self.getCollection(collection_name=collection_name, db_name=db_name)
previous_records = self.findAllRecords(db_name=db_name, collection_name=collection_name)
new_records = query
updated_record = collection.update_one(previous_records, new_records)
return updated_record
except Exception as e:
raise Exception(
f"(updateRecord): Failed to update the records with given collection query or database name.\n" + str(
e))
def updateMultipleRecord(self, db_name, collection_name, query):
"""
"""
try:
collection_check_status = self.isCollectionPresent(collection_name=collection_name, db_name=db_name)
if collection_check_status:
collection = self.getCollection(collection_name=collection_name, db_name=db_name)
previous_records = self.findAllRecords(db_name=db_name, collection_name=collection_name)
new_records = query
updated_records = collection.update_many(previous_records, new_records)
return updated_records
except Exception as e:
raise Exception(
f"(updateMultipleRecord): Failed to update the records with given collection query or database name.\n" + str(
e))
def deleteRecord(self, db_name, collection_name, query):
"""
"""
try:
collection_check_status = self.isCollectionPresent(collection_name=collection_name, db_name=db_name)
if collection_check_status:
collection = self.getCollection(collection_name=collection_name, db_name=db_name)
collection.delete_one(query)
return "1 row deleted"
except Exception as e:
raise Exception(
f"(deleteRecord): Failed to update the records with given collection query or database name.\n" + str(
e))
def deleteRecords(self, db_name, collection_name, query):
"""
"""
try:
collection_check_status = self.isCollectionPresent(collection_name=collection_name, db_name=db_name)
if collection_check_status:
collection = self.getCollection(collection_name=collection_name, db_name=db_name)
collection.delete_many(query)
return "Multiple rows deleted"
except Exception as e:
raise Exception(
f"(deleteRecords): Failed to update the records with given collection query or database name.\n" + str(
e))
def getDataFrameOfCollection(self, db_name, collection_name):
"""
"""
try:
all_Records = self.findAllRecords(collection_name=collection_name, db_name=db_name)
dataframe = pd.DataFrame(all_Records)
return dataframe
except Exception as e:
raise Exception(
f"(getDataFrameOfCollection): Failed to get DatFrame from provided collection and database.\n" + str(e))
def saveDataFrameIntoCollection(self, collection_name, db_name, dataframe):
"""
"""
try:
collection_check_status = self.isCollectionPresent(collection_name=collection_name, db_name=db_name)
dataframe_dict = json.loads(dataframe.T.to_json())
if collection_check_status:
self.insertRecords(collection_name=collection_name, db_name=db_name, records=dataframe_dict)
return "Inserted"
else:
self.createDatabase(db_name=db_name)
self.createCollection(collection_name=collection_name, db_name=db_name)
self.insertRecords(db_name=db_name, collection_name=collection_name, records=dataframe_dict)
return "Inserted"
except Exception as e:
raise Exception(
f"(saveDataFrameIntoCollection): Failed to save dataframe value into collection.\n" + str(e))
def getResultToDisplayOnBrowser(self, db_name, collection_name):
"""
This function returns the final result to display on browser.
"""
try:
response = self.findAllRecords(db_name=db_name, collection_name=collection_name)
result = [i for i in response]
return result
except Exception as e:
raise Exception(
f"(getResultToDisplayOnBrowser) - Something went wrong on getting result from database.\n" + str(e))