安装
使用之前,要确保已经安装好了MongoDB并启动了其服务,同时安装好了Python的PyMongo库。
可以参考:https://cuiqingcai.com/5205.html
安装PyMongo
pip install pymongo
连接MongoDB
连接MongoDB时,需要使用过PyMongo库里面的MongoClient。只需要向其传入MongoDB的IP及端口即可,其中第一个参数为地址host,第二个参数为port(默认27017)
import pymongoclient = pymongo.MongoClient(host='localhost', port=27017)
也可以
client = MongoClient('mongodb://localhost:27017/')
指定数据库
MongoDB中可以建立多个数据库,接下来我们需要指定操作其中一个数据库。以test数据库为例
db = client.test# 也可以写成db = client['test']
指定结合
MongoDB的每个数据库包含许多集合,类似于关系型数据库中的表。
指定一个名称为students的集合
collection = db.students# 也可以写成collection = db['students']
插入数据
示例
- 对students这个集合新建一条学生数据
student = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}
调用collection的insert方法即可插入数据
result = collection.insert(student)print(result)
在MongoDB中,每条数据都有一个_id属性来唯一标识。如果没有显式指明该属性,MongoDB会自动产生一个ObjectId类型的_id属性。
插入多条数据,只需以列表的形式传递即可
student1 = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}student2 = { 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}result = collection.insert([student1, student2])print(result)
运行结果
[ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]
注:PyMongo中,官方不推荐使用insert方法,推荐使用insert_one和insert_many方法。
查询
插入数据后,可以利用find_one或find方法进行查询。
示例
result = collection.find_one({'name': 'Mike'})print(type(result))print(result)
运行结果
<class 'dict'>{'_id': ObjectId('5932a80115c2606a59e8a049'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
多条数据的查询,可以使用find方法
示例
- 查找年龄为20的数据
results = collection.find({'age': 20})print(results)for result in results: print(result)
运行结果
object at {'_id': ObjectId('593278c115c2602667ec6bae'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}{'_id': ObjectId('593278c815c2602678bb2b8d'), 'id': '20170102', 'name': 'Kevin', 'age': 20, 'gender': 'male'}{'_id': ObjectId('593278d815c260269d7645a8'), 'id': '20170103', 'name': 'Harden', 'age': 20, 'gender': 'male'
返回结果是cursor类型,相当于一个生成器。
- 查询年龄大于20的数据
results = collection.find({'age': {'$gt': 20}})
$gt意思是大于
比较符号归纳
- 查询名义以M开头的学生数据
results = collection.find({'name': {'$regex': '^M.*'}})
功能符号归纳