-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongo.py
85 lines (63 loc) · 2.34 KB
/
mongo.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
from pymongo import MongoClient
# 创建数据库连接
conn = MongoClient('localhost',27017)
# 创建数据库对象和集合对象
db = conn.stu
myset = db.class4
# 数据操作
# ********* insert ************
# myset.insert_one({'name':'张铁林','King':'乾隆'})
# myset.insert_many([{'name':'陈道明','King':'康熙'},
# {'name':'张国立','King':'康熙'}
# ])
# myset.insert({"name":'唐国强',"King":'雍正'})
# myset.insert([{"name":'陈建斌',"King":'雍正'},
# {"name":'聂远','King':"乾隆"}])
# myset.save({'_id':1,'name':'吴奇隆',"King":'四爷'})
# myset.save({'_id':1,'name':'郑少秋',"King":'乾隆'})
# ***************** find *******************
# 所有的操作符加引号,作为字符串表达
cursor = myset.find({'name':{'$gt':'唐国强'}},{'_id':0})
# 循环遍历得到的每一个结果都是文档字典
# for i in cursor:
# print(i['name'],'---',i['King'])
# print(cursor.next()) # 获取游标的下一个结果
# cursor调用limit,skip,sort后得到的仍然是结果游标对象
# for i in cursor.skip(1).limit(3):
# print(i)
# 按照king排序
# for i in cursor.sort([('King',1)]):
# print(i)
# r = myset.find_one({'King':'康熙'},{"_id":0})
# print(r)
# ******************** update ****************
# myset.update_one({"King":'康熙'},{'$set':{"king_name":'玄烨'}})
#
# myset.update_many({"King":'雍正'},{"$set":{'king_name':'胤禛'}})
# myset.update({"King":'乾隆'},{"$set":{'king_name':'弘历'}},multi = True)
# myset.update_one({"King":'光绪'},
# {'$set':{"name":'邓超'}},upsert = True)
# ******************* delete *******************
# myset.delete_one({'King':'乾隆'})
# myset.delete_many({"king_name": None})
# myset.remove({"King":'雍正'}, multi = False)
# r = myset.find_one_and_delete({'King':'乾隆'})
# print(r)
# ********************* index ************************
# 参数 'name' ==> [('name', 1)]
# index1 = myset.create_index('name')
# index2 = myset.create_index([('name', -1)], name = 'NAME', sparse = True)
#
# print("index1 = ", index1)
# print("index2 = ", index2)
#
# 删除索引
# myset.drop_index('NAME')
# myset.drop_index([("name", 1)])
# myset.drop_indexes()
# 查看索引
# for i in myset.list_indexes():
# print(i)
# ************* aggregation *******************
# 关闭连接
conn.close()