forked from ishantk/GW2022PD1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSession21.py
95 lines (73 loc) · 2.5 KB
/
Session21.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
import pymongo
class Customer:
def __init__(self, name=None, phone=None, email=None, age=None, gender=None):
self.name = name
self.phone = phone
self.email = email
self.age = age
self.gender = gender
class MongoDBHelper:
def __init__(self):
client = pymongo.MongoClient(
"mongodb+srv://atpl:[email protected]/?retryWrites=true&w=majority")
# Select the DataBase in MongoDB
self.db = client['gw2022pd1']
# From the MongoDB Select the Collection
self.collection = self.db['customers']
def insert(self, document):
result = self.collection.insert_one(document)
# print(result, type(result))
print("Inserted Data:", result.inserted_id)
def fetch(self):
rows = []
documents = self.collection.find()
print(documents, type(documents))
for document in documents:
print(document, type(document))
rows.append(document)
# list of dictionary
return rows
def fetch_selected(self, query):
rows = []
documents = self.collection.find(query)
print(documents, type(documents))
for document in documents:
print(document, type(document))
rows.append(document)
# list of dictionary
return rows[0]
def delete(self, query):
result = self.collection.delete_one(query)
print(result.deleted_count)
def update(self, document, query):
update_query = {"$set": document}
result = self.collection.update_one(query, update_query)
print(result.modified_count)
def main():
db_helper = MongoDBHelper()
customer1 = Customer(name="Shawn", phone="7777755555",
email="[email protected]", age=23, gender="male")
customer1.subjects = [
{
"name": "Physics",
"marks": 90
},
{
"name": "Maths",
"marks": 90
}
]
# customer_dictionary = vars(customer1)
# print(customer_dictionary, type(customer_dictionary))
#
# db_helper.insert(document=customer_dictionary)
db_helper.fetch()
# query = {"phone": "9999955555"}
# db_helper.fetch_selected(query)
# db_helper.delete(query)
# query = {"phone": "8888855555"}
# db_helper.update(document=customer_dictionary, query=query)
# query = {"age": {"$gte": 22}}
# db_helper.fetch_selected(query)
if __name__ == "__main__":
main()