fangxiaoji 2020-01-30
进入虚拟环境 sudo pip install pymongo 或源码安装 python setup.py
import pymongo
类MongoClient
无安全认证:client=pymongo.MongoClient(‘mongodb://localhost:27017‘)
有安全认证:client=pymongo.MongoClient(‘mongodb://用户名:密码@localhost:27017/数据库名称‘)
类database
db=client.test1
类collection
stu = db.stu
s1={name:‘gj‘,age:18} s1_id = stu.insert_one(s1).inserted_idprint(s1_id)
scores.update_one({‘name‘:‘zsf‘},{‘$set‘:{‘name‘:‘张三丰‘}})
scores.delete_one({‘name‘:‘zsf‘})
ret = stu.find_one()
print(ret)print(ret[‘name‘])ret = stu.find_one({‘name‘:‘张三丰‘})print(ret)print(ret[‘name‘])
cursor = stu.find()for s in cursor: print(s) print(s[‘name‘])cursor = stu.find({‘name‘:‘张三丰‘})for s in cursor: print(s) print(s[‘name‘])
cur=stu.find() cur.next() cur.next() cur.next()
print stu.count()
单属性:cur = stu.find().sort(‘age‘, DESCENDING)
多属性:cur = stu.find().sort([(‘age‘, DESCENDING),(‘name‘, ASCENDING)])
cur=stu.find().skip(2).limit(3)
# -*- coding:utf-8 -*- # @Time : 2020/1/29 23:16 # @Author : xxxx # @File : test1_mongodb.py # @Software: PyCharm import pymongo def test0(): # 获取客户端,建立连接 cli = pymongo.MongoClient(‘mongodb://localhost:27017‘) # 切换数据库 db = cli.liuyan # 获取集合 scores = db.scores # 添加 scores.insert_one({‘name‘:‘张一丰‘}) # 删除 scores.delete_one({‘name‘:‘张一丰‘}) # 修改 scores.update_one({‘name‘:‘zsf‘},{‘$set‘:{‘name‘:‘张三丰‘}}) def test1(): # 获取客户端,建立连接 cli = pymongo.MongoClient(‘mongodb://localhost:27017‘) # 切换数据库 db = cli.liuyan # 获取集合 scores = db.scores # 查询 ret = scores.find_one() print(ret) print(ret[‘name‘]) def test2(): # 获取客户端,建立连接 cli = pymongo.MongoClient(‘mongodb://localhost:27017‘) # 切换数据库 db = cli.liuyan # 获取集合 scores = db.scores # 查询 ret = scores.find_one({‘name‘:‘张三丰‘}) print(ret) print(ret[‘name‘]) def test3(): # 获取客户端,建立连接 cli = pymongo.MongoClient(‘mongodb://localhost:27017‘) # 切换数据库 db = cli.liuyan # 获取集合 scores = db.scores # 查询 cursor = scores.find() for s in cursor: print(s) print(s[‘name‘]) def test4(): # 获取客户端,建立连接 cli = pymongo.MongoClient(‘mongodb://localhost:27017‘) # 切换数据库 db = cli.liuyan # 获取集合 scores = db.scores # 查询 cursor = scores.find({‘name‘:‘张三丰‘}) for s in cursor: print(s) print(s[‘name‘]) def test5(): # 获取客户端,建立连接 cli = pymongo.MongoClient(‘mongodb://localhost:27017‘) # 切换数据库 db = cli.liuyan # 获取集合 scores = db.scores # 查询 # ret = scores.find({‘age‘:{‘$gt‘:20}}) # for s in ret: # print(s[‘name‘]) def test6(): # 获取客户端,建立连接 cli = pymongo.MongoClient(‘mongodb://localhost:27017‘) # 切换数据库 db = cli.liuyan # 获取集合 scores = db.scores # 查询、排序 # cursor = scores.find().sort(‘name‘, pymongo.DESCENDING) cursor = scores.find().sort([(‘name‘, pymongo.DESCENDING), (‘age‘, pymongo.ASCENDING)]) for s in cursor: # print(s) print(s[‘name‘]) if __name__ == ‘__main__‘: # test0() # test1() # test2() # test3() # test4() # test5() test6()