1. 安装pymongo
pip install pymongo -i https://pypi.douban.com/simple
2. 连接数据库
- 第一种办法
import pymongo
client = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
- 第二种办法
import pymongo
client = pymongo.MongoClient(host='127.0.0.1',port='27017')
输出结果
MongoClient(host=['127.0.0.1:27017'], document_class=dict, tz_aware=False, connect=True)
3. 指定数据库
db = client.test
等价于
db = client['test']
4. 指定集合
collection = db.students
等价于
collection = db['students']
5. 插入数据
- 插入一条数据
student = {
'id': '2019081501',
'name': 'caixukun',
'hobby': 'sing,dance,rap,basketball',
'gender': 'male'
}
result = collection.insert(student)
# 或result = collection.insert_one(student)
print(result)
运行结果
5d5431f5f00e7b113768c78c
- 插入多条数据
student1 = {
'id': '2019081502',
'name': 'caixukun',
'hobby': 'sing',
'gender': 'male'
}
student2 = {
'id': '2019081503',
'name': 'caixukun',
'hobby': 'dance',
'gender': 'male'
}
result = collection.insert_many([student1, student2])
print(result)
print(result.inserted_ids)
输出结果
<pymongo.results.InsertManyResult object at 0x0000027B17D13848>
[ObjectId('5d5432d3689a185dda711cfa'), ObjectId('5d5432d3689a185dda711cfb')]
6. 查询数据
- 查询一条数据
result = collection.find_one({'name': 'caixukun'})
print(result)
输出结果
{'_id': ObjectId('5d5431f5f00e7b113768c78c'), 'id': '2019081501', 'name': 'caixukun', 'hobby': 'sing,dance,rap,basketball', 'gender': 'male'}
返回类型为dict
如果查询结果不存在,则返回None
- 查询多条数据
results = collection.find({'name': 'caixukun'})
print(results)
for result in results:
print(result)
输出结果
<pymongo.cursor.Cursor object at 0x000001F9FD4E8F98>
{'_id': ObjectId('5d5431f5f00e7b113768c78c'), 'id': '2019081501', 'name': 'caixukun', 'hobby': 'sing,dance,rap,basketball', 'gender': 'male'}
{'_id': ObjectId('5d5432d3689a185dda711cfa'), 'id': '2019081502', 'name': 'caixukun', 'hobby': 'sing', 'gender': 'male'}
{'_id': ObjectId('5d5432d3689a185dda711cfb'), 'id': '2019081503', 'name': 'caixukun', 'hobby': 'dance', 'gender': 'male'}
查询数据可以使用一些比较符号
如results = collection.find({'id': {'$gt': '2019081502'}})
常用符号,如下表:
符号 | 含义 |
---|---|
$lt | 小于 |
$gt | 大于 |
$lte | 小于等于 |
$gte | 大于等于 |
$in | 在范围内 |
$nin | 不在范围内 |
$regex | 匹配正则表达式 |
7. 计数
count = collection.find().count()
print(count)
8. 排序
results = collection.find().sort('hobby', pymongo.ASCENDING)
pymongo.ASCENDING 指升序
pymongo.DESCENDING 指降序
9. 删除
result = collection.remove({'hobby': 'sing'})
print(result)
输出结果
# 指成功删除一条,n为删除条数
{'n': 1, 'ok': 1.0}
还可以使用
result = collection.delete_one({'hobby': 'sing'})
results = collection.delete_many({'id': {'$gt': '2019081502'}})