首先关于MongoDB安装于配置,由于MongoDB已经升级到4.x版本所以下面给出关于4.x的安装于配置
关于python连接到MongoDB使用PyMongo库
安装方法
pip3 install PyMongo
连接时用PyMongo的MongoClient方法,传入地址及端口,没声明端口则默认为27017
import pymongo
client=pymongo.MongoClient(host='localhost',port=27017)
当然也可以传入一个连接字符串
client=MongoClient('mongodb://localhost:27017/')
指定数据库
首先先指定一个数据库例如指定test数据库
db=client.test#or client['test']
指定集合
类比于指定数据库
collection=db.students#or collection=db['students']
插入数据
这里注意一点因为MongoDB在4.x以上的版本删除了insert的插入方法所以应当用insert_one或者insert_many
错误举例:
student={
'id':'54646',
'name':'tom',
'age':'20'
}
result=collection.insert(student)
Traceback (most recent call last):
File "C:\Users\FrostMag\Desktop\爬虫\csv存储.py", line 11, in <module>
result=collection.insert(student)
File "C:\Users\FrostMag\Desktop\爬虫\venv\lib\site-packages\pymongo\collection.py", line 3169, in __call__
"failing because no such method exists." % self.__name.split(".")[-1]
TypeError: 'Collection' object is not callable. If you meant to call the 'insert' method on a 'Collection' object it is failing because no such method exists.
直接报错
正确方法
student={
'id':'54646',
'name':'tom',
'age':'20'
}
result=collection.insert_one(student)
这里返回的是一个InsertOneResult对象,在MongoDB中每条数据对应一个编码,使用inserted_id 如果是many则为ids可查看
查询
查询的方法有find_one或者find 前者查询得到的单个结果,后者返回一个生成器对象
result=collection.find_one({'name':'tom'})
print(type(result))
print(result)
<class 'dict'>
{'_id': ObjectId('638c4b690ac5056d54301f69'), 'id': '54646', 'name': 'tom', 'age': '20'}
也可以用objectid来查询
from bson.objectid import ObjectId
result=collection.find_one({'_id':ObjectId('638c4b690ac5056d54301f69')})
print(result)
结果都一样
若查询多个数据可以用find方法但因为生成的是生成器所以用循环语句输出
在这里将比较符号归纳如下表:
符号含义示例
$lt小于{'age': {'$lt': 20}}
$gt大于{'age': {'$gt': 20}}
$lte小于等于{'age': {'$lte': 20}}
$gte大于等于{'age': {'$gte': 20}}
$ne不等于{'age': {'$ne': 20}}
$in在范围内{'age': {'$in': [20, 23]}}
$nin不在范围内{'age': {'$nin': [20, 23]}}
另外还可以进行正则匹配查询,例如查询名字以M开头的学生数据,示例如下:
results= collection.find({'name': {'$regex':'^M.*'}})
在这里使用了$regex来指定正则匹配,^M.*代表以M开头的正则表达式,这样就可以查询所有符合该正则的结果。
在这里将一些功能符号再归类如下:
符号含义示例示例含义
$regex匹配正则{'name': {'$regex': '^M.*'}}name以M开头
$exists属性是否存在{'name': {'$exists': True}}name属性存在
$type类型判断{'age': {'$type': 'int'}}age的类型为int
$mod数字模操作{'age': {'$mod': [5, 0]}}年龄模5余0
$text文本查询{'$text': {'$search': 'Mike'}}text类型的属性中包含Mike字符串
计数
用于查询结果包含多少数据
注意!!!在新版的MongoDB中删除了count方法查询
应当用estimated_document_count()和count_documents()前者用来查询集合的所以数据后者是选择性查询
count=collection.estimated_document_count()
print(count)
count=collection.count_documents({'age':'20'})
print(count)
排序
排序调用sort方法传入排序对象和排序法则
student1={
"name":"john",
"age":"20"
}
student2={
"id":"54646",
"name":"mike",
"age":"20"
}
cilent=pymongo.MongoClient(host='localhost',port=27017)
db=cilent.test
collection=db.students
result=collection.insert_many([student1,student2])
results=collection.find().sort('name',pymongo.ASCENDING)
print([result['name'] for result in results])
如果是降序则标明pymongo.DESCENDINC
偏移
使用skip方法,忽略前x个元素提取后面的全部元素
results=collection.find().sort('name',pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])
当然也可以用limit方法限制输出个数
results=collection.find().sort('name',pymongo.ASCENDING).skip(2).limit(2)
print([result['name'] for result in results])
数据库很大时最好用查询
更新
用update方法进行更新
步骤:1指定查询条件
2查询出结果
3修改结果
4将条件和修改的数据传入update_one或update_many中(第二个参数要使用$类型操作符作为键名) 前者只会更新匹配的第一条,后者会更新所有
例子
condition={'name':'mike'}
student=collection.find_one(condition)
student['age']='15'
result=collection.update_one(condition,{'$set': student})
print(result.matched_count, result.modified_count)
输入用*.matched(匹配)_count *.modified(修改)_count方法
这里传入的$set用于只更新字典内存在的字段,如果原先有则不会更新,不加的话另说
condition={'age':{'$gt':20}}
result=collection.update_one(condition,{'$inc':{'age':1}})
print(result)
print(result.matched_count,result.modified_count)
这里表示选择年龄大于20的数据并结果加一
删除
删除操作用remove方法即可(符合匹配的全部删除)但我这里会报错估计新版把方法也删了
官方推荐两种方法delete_one()和delete_many()前面删除匹配到到的第一个后者删除匹配到的所有
result=collection.delete_many({'age':'15'})
print(result.deleted_count)
---------------------------------------------------------------------------------------------------------------------------------
本专栏是我学习爬虫的笔记,因本人才大一如有错误欢迎大佬指出