-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongodb.py
86 lines (71 loc) · 2.41 KB
/
mongodb.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
import pymongo
class MongoDBCollection:
def __init__(self,
username,
password,
ip_address,
database_name,
collection_name):
'''
Using ip_address, database_name, collection_name,
initiate the instance's attributes including ip_address,
database_name, collection_name, client, db and collection.
For pymongo, see more details in the following.
https://pymongo.readthedocs.io
'''
self.username = username
self.password = password
self.ip_address = ip_address
self.database_name = database_name
self.collection_name = collection_name
self.client = pymongo.MongoClient(f"mongodb+srv://{username}:{password}@{ip_address}")
self.db = self.client[self.database_name]
self.collection = self.db[self.collection_name]
self.connection_string = f"mongodb+srv://{username}:{password}@{ip_address}/{database_name}.{collection_name}"
def return_db(self):
'''
Return db which is the database in the client
'''
return self.db
def return_collection(self):
'''
Return db which belongs to the db.
'''
return self.collection
def return_num_docs(self, query):
'''
Return the number of documents satisfying the given query.
'''
return self.collection.count_documents(query)
def drop_collection(self):
'''
Drop the collection
'''
return self.collection.drop()
def find(self, query, projection):
'''
Return an iteratatable using query and projection.
'''
for item in self.collection.find(query, projection):
yield item
def insert_one(self, doc):
'''
Insert the given document
'''
self.collection.insert_one(doc)
def insert_many(self, docs):
'''
Insert the given documents
'''
self.collection.insert_many(docs)
def update_many(self, filter, update):
'''
Update documents satisfying filter with update.
Both filter and update are dictionaries.
'''
self.collection.update_many(filter, update)
def delete_many(self, filter):
'''
Remove documents satisfying filter with delete.
'''
self.collection.delete_many(filter)