0%

python-mongodb

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
from pymongo import MongoClient

class TestMongo:
def __enter__(self):
self.__client = MongoClient(host="127.0.0.1",port=27017)
self.collection = self.__client['test']["t1"] #使用方括号选择数据库和集合

def __exit__(self, exc_type, exc_val, exc_tb):
self.__client.close()

def test_insert(self):
#insert接收字典,返回ObjectID
ret = self.collection.insert({"name":"lily","age":17})
return ret

def test_insert_many(self):
item_list = [{"name":f"test{i}" for i in range(10)}]
#isnert_many接收列表,列表中为需要插入的字典
ret_list = self.collection.insert_many(item_list)
#ret_list.inserted_ids为一个列表,包括所有插入数据的id
return ret_list.inserted_ids

def try_find_one(self):
#find_one返回一个结果,接收一个字典形式的字典
t = self.collection.find_one({"name":"test5"})
return t

def try_find_many(self):
#返回所有结果,若条件为空,返回所有数据
t = self.collection.find()
#返回一个Cursor游标
for i in t:
print(i)
for j in t:
print(j) #由于上面游标已经移到最后一个,不会再有输出
print(list(t)) #可以强转

def try_update_one(self):
self.collection.update_one({"name":"test5"},{"$set":{"name":"new_test5"}})

def try_update_many(self):
self.collection.update_many({"name": "test5"}, {"$set": {"name": "new_test5"}})

def try_delete_one(self):
self.collection.delete_one({"name":"test5"})

def try_delete_many(self):
self.collection.delete_many({"name":"test5"})