MongoDB-python的API手记

158 阅读2分钟
-------------------python调用MongoDB-------------------



2、linux下安装指令:sudo pip install pymongo


3、测试python驱动:

[AppleScript]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
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
1 #coding=utf-8
2
3 '''
4 测试python驱动
5 '''
6
7 #引用对应的包
8 import pymongo
9
10 #创建一个mongo客户端对象
11 client = pymongo.MongoClient("127.0.0.1",27017)
12 #获得mongoDB中的数据库对象
13 db = client.test_database
14 #在数据库中创建一个集合
15 collection = db.test_collectionTwo
16
17 #创建一条要加入数据库中的数据信息,json格式
18 post_data = {"username":"xiaohao","pwd":"123456",}
19
20 #进行数据的添加操作,inserted_id返回添加后的id编号信息
21 post_data_id = collection.insert_one(post_data).inserted_id
22
23 #展示一下插入的数据信息
24 print collection.find_one()
25
26 #打印当前数据库中所有集合的民称
27 print db.collection_names()
28
29 #打印当前集合中数据的信息
30 for item in collection.find():
31 print item
32
33 #打印当前集合中数据的个数
34 print collection.count()
35
36 #进行find查询,并打印查询到的数据的条数
37 print collection.find({"username":"xiaohao"}).count()
4、Aggregation Examples:mongoDB聚合练习
[AppleScript]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
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
1 #coding=utf-8
2
3 '''
4 进行聚合aggregation 练习
5 '''
6
7 #引包
8 import pymongo
9
10 client = pymongo.MongoClient("127.0.0.1",27017)
11
12 db = client.aggregation_database
13
14 collection = db.aggregation_collection
15
16 collection.insert_many([
17 {"username":"xiaohao01","pwd":"111"},
18 {"username":"xiaohao02","pwd":"222"},
19 {"username":"xiaohao03","pwd":"333"}
20 ])
21
22
23 # for item in collection.find():
24 # print item
25
26 #python中不含有son语法,需要使用son

更多技术资讯可关注:itheimaGZ获取