-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdatabaseoperation.py
More file actions
76 lines (59 loc) · 1.81 KB
/
databaseoperation.py
File metadata and controls
76 lines (59 loc) · 1.81 KB
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
import pymongo
from bson import ObjectId
# Connected Database
connection = pymongo.MongoClient('localhost', 27017)
# create Database
database = connection['mydb_01']
# create Collection
collection =database['mycol_01']
print("database connected")
def insert_record(data):
document = collection.insert_one(data)
return document.inserted_id
def update_or_create(document_id, data):
document = collection.update_one({'_id': ObjectId(document_id)}, {"$set": data}, upsert=True)
return document.acknowledged
def update_existing(document_id, data):
document = collection.update_one({'_id': ObjectId(document_id)}, {"$set":data})
return document.acknowledged
def get_single_record(document_id):
data= collection.find_one({'_id': ObjectId(document_id)})
return data
def get_multiple_record():
data = collection.find()
return list(data)
def remove_record(document_id):
document = collection.delete_one({'_id': ObjectId(document_id)})
return document.acknowledged
# Close Database
connection.close()
# # insert record
# data = {"Name": "Arun","Address": "goregoan"}
# id = insert_record(data)
# print(id)
#
# # retrive sepecific record
# document_id ='5e7b16e13b61b22a8d54c2b5'
# record= get_single_record(document_id)
# print(record)
#
# # retrive all record
# record = get_multiple_record()
# print(record)
#
# # update specific record
# document_id ='5e7b16e13b61b22a8d54c2b5'
# data = {'Name': 'Hiren'}
# ack = update_existing(document_id, data)
# print(ack)
#
# # remove specific record
# document_id ='5e7b16e13b61b22a8d54c2b5'
# ack = remove_record(document_id)
# print(ack)
#
# # update specific record if not exist _id then create records.
# document_id ='5e7b16e13b61b22a8d54c2b5'
# data = {'Name': 'Hiren',"Address": "vivar"}
# ack = update_or_create(document_id, data)
# print(ack)