使用pymongo操作MongoDB



MongoDB:由C++编写的非关系型数据库,是基于分布式额、文件存储的开源数据库系统
pymongo:python中的操作MongoDB的第三方库



1. 准备工作



我们在用pymongo实现操作MongoDB之前,要保证已经安装好MongoDB并已经启动其服务



2. 连接MongoDB



连接MongoDB时,我们需要使用PyMongo库里面的MongoClient
import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)  #host为地址,port为端口(port的默认参数为27017)



3. 指定数据库



MongoDB中可以有很多的数据库,我们需要指定操作哪个数据库



我们以text数据库为例:



import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)  #host为地址,port为端口(port的默认参数为27017)         
db = client.test  #指定text数据库
collection = db.students
student = {
    'id':'20170101',
    'name':'huquan',
    'age':22,
    'gender':'male'
}
result = collection.insert_one(student)
print(result.inserted_id)
5b55e9bed527281c18dc5185



4. 指定集合

指定集合students,声明collection对象



import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)  #host为地址,port为端口(port的默认参数为27017)         
db = client.test  #指定text数据库
collection = db.students  #指定集合



5. 插入数据

在students集合里、新建数据,调用insert_one和insert_many分别插入单条数据和多条数据



import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)  #host为地址,port为端口(port的默认参数为27017)         
db = client.test  #指定text数据库
collection = db.students  #指定集合
student = {
    'id':'20170101',
    'name':'huquan',
    'age':22,
    'gender':'male'
}
result = collection.insert_one(student)  #插入单条数据
print(result)
print(result.inserted_id)  #输出单个数据id

print('--------我是分割线--------')
student1 = {
    'id':'20170201',
    'name':'yaorui',
    'age':23,
    'gender':'male'
}
student2 = {
    'id':'20170306',
    'name':'jiangcheng',
    'age':24,
    'gender':'male'
}
result = collection.insert_many([student1,student2]) #插入多条数据
print(result)
print(result.inserted_ids)  #输出多个数据id
<pymongo.results.InsertOneResult object at 0x00000000055D0408>
5b55e9bed527281c18dc5188
--------我是分割线--------
<pymongo.results.InsertManyResult object at 0x0000000005643B88>
[ObjectId('5b55e9bed527281c18dc5189'), ObjectId('5b55e9bed527281c18dc518a')]



6. 查询

利用find()或find_one来查询数据



find_one:查询返回单条数据
find:查询多条数据,返回的是一个生成器对象
import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)  
db = client.test 
collection = db.students  
result = collection.find_one({'name':'huquan'})#查询单条数据
print(result)
results=collection.find({'gender':'male'})  #查询生成一个生成器
for result in results:  #遍历输出
    print(result)
print('------- 我 是 分 割 线 --------')
results = collection.find({'age':{'$lt':23}})  #查询年龄小于23的数据
for result in results:  #遍历输出
    print(result)
{'_id': ObjectId('5b55e9bed527281c18dc5185'), 'id': '20170101', 'name': 'huquan', 'age': 22, 'gender': 'male'}
{'_id': ObjectId('5b55e9bed527281c18dc5185'), 'id': '20170101', 'name': 'huquan', 'age': 22, 'gender': 'male'}
{'_id': ObjectId('5b55e9bed527281c18dc5188'), 'id': '20170101', 'name': 'huquan', 'age': 22, 'gender': 'male'}
{'_id': ObjectId('5b55e9bed527281c18dc5189'), 'id': '20170201', 'name': 'yaorui', 'age': 23, 'gender': 'male'}
{'_id': ObjectId('5b55e9bed527281c18dc518a'), 'id': '20170306', 'name': 'jiangcheng', 'age': 24, 'gender': 'male'}
------- 我 是 分 割 线 --------
{'_id': ObjectId('5b55e9bed527281c18dc5185'), 'id': '20170101', 'name': 'huquan', 'age': 22, 'gender': 'male'}
{'_id': ObjectId('5b55e9bed527281c18dc5188'), 'id': '20170101', 'name': 'huquan', 'age': 22, 'gender': 'male'}



比较符号归纳:



符 号        含 义              示 例
..................................................
    $lt         小于         {'age':{'$lt':23}}  
$gt         大于         {'age':{'$gt':23}}  
$lte        小于等于     {'age':{'$lte':23}}  
$gte        大于等于     {'age':{'$gte':23}}  
$ne         不等于       {'age':{'$ne':23}}  
$in         在范围内     {'age':{'$in':[20,23]}} 
$nin        不在范围内    {'age':{'$nin':[20,23]}}



7. 计数



import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)  #host为地址,port为端口(port的默认参数为27017)         
db = client.test  #指定text数据库
collection = db.students  #指定集合
count=collection.find().count()   #查询所有数据
print(count)
count = collection.find({'name':'huquan'}).count()   #查询某个条件的数据
print(count)
4
2


C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:5: DeprecationWarning: count is deprecated. Use Collection.count_documents instead.
  """
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:7: DeprecationWarning: count is deprecated. Use Collection.count_documents instead.
  import sys



8. 排序



调用sort()方法
import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)  #host为地址,port为端口(port的默认参数为27017)         
db = client.test  #指定text数据库
collection = db.students  #指定集合
results = collection.find().sort('age',pymongo.ASCENDING)
print([result['age'] for result in results])  #顺序输出
print('--------我 是 分 割 线----------')
results = collection.find().sort('age',pymongo.ASCENDING)
for result in results:
    print(result)
[22, 22, 23, 24]
--------我 是 分 割 线----------
{'_id': ObjectId('5b55e9bed527281c18dc5185'), 'id': '20170101', 'name': 'huquan', 'age': 22, 'gender': 'male'}
{'_id': ObjectId('5b55e9bed527281c18dc5188'), 'id': '20170101', 'name': 'huquan', 'age': 22, 'gender': 'male'}
{'_id': ObjectId('5b55e9bed527281c18dc5189'), 'id': '20170201', 'name': 'yaorui', 'age': 23, 'gender': 'male'}
{'_id': ObjectId('5b55e9bed527281c18dc518a'), 'id': '20170306', 'name': 'jiangcheng', 'age': 24, 'gender': 'male'}



9. 偏移



在有些时候,我们可能只想取某几个元素,这时可以用skip()方法偏移几个位置,比如偏移2个位置,就是忽略前两个元素,得到第三个元素及以后的元素:
还有可以使用limit()方法,指定返回结果的个数
import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)  #host为地址,port为端口(port的默认参数为27017)         
db = client.test  #指定text数据库
collection = db.students  #指定集合
results = collection.find().sort('age',pymongo.ASCENDING).skip(2)  # 忽略前两个元素
print([result['age']for result in results])
print('--------我 是 分 割 线----------')
results = collection.find().sort('age',pymongo.ASCENDING).skip(2).limit(2)  #返回前两个结果
print([result['age']for result in results])
[23, 24]
--------我 是 分 割 线----------
[23, 24]



10. 更新



对于数据的更新,我们可以使用update_one()方法和update_many()方法
import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)
collection = client.test.students
condition = {'name':'huquan'}
student = collection.find_one(condition)
student['age'] = 26
result = collection.update_one(condition,{'$set':student})
print(result)
print(result.matched_count,result.modified_count)
<pymongo.results.UpdateResult object at 0x0000000005643188>
1 1



11. 删除



delete_one()
delete_many()
import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)
collection = client.test.students
result = collection.delete_one({'age':22})
print(result.deleted_count)  #删除的个数
result = collection.delete_many({'age':23})
print(result.deleted_count)  #删除的个数
1
1