作者:娜一刻冻杰幸福 | 来源:互联网 | 2023-02-08 18:07
1importpymongo234classMyMonDb(object):5def__init__(self,db_name,col_name):6self.connpymon
1 import pymongo
2
3
4 class MyMonDb(object):
5 def __init__(self, db_name, col_name):
6 self.cOnn= pymongo.MongoClient()
7 self.db_name = self.conn[db_name]
8 self.col_name = self.db_name[col_name]
9
10 def insert(self, data):
11 if isinstance(data, list):
12 self.col_name.insert_many(data)
13 elif isinstance(data, dict):
14 self.col_name.insert_one(data)
15
16 def delete(self, query, _all=False):
17 if _all:
18 self.col_name.delete_many(query)
19 else:
20 self.col_name.delete_one(query)
21
22 def update(self, query, data):
23 self.col_name.update_many(query, data)
24
25 def find(self, query, _all=False):
26 if _all:
27 return self.col_name.find(query)
28 else:
29 return self.col_name.find_one(query)
30
31
32 if __name__ == '__main__':
33 m = MyMonDb("gkl", "students")
34 m.insert([{"_id": 6, "name": "gkl"}, {"_id": 7, "name": "rfy"}])
35 m.update({"name":"rfy"}, {"$set": {"name": "郭康伦"}})
36 for i in m.find({}, _all=True):
37 print(i)