MongoDB是由C++语言编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统
MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。
MongoDB 文档类似于JSON 对象。字段值可以包含其他文档,数组及文档数组
PyMongo库里面的MongoClient,默认是27017
一、术语
SQL术语 MongoDB术语 说明
database database 数据库
table collection 数据库表/集合
row document 数据记录行/文档
colunmn field 数据字段/域
index index 索引
二、PyMongo模块常用方法
1、安装
安装 python3 -m pip3 install pymongo
指定版本安装 python3 -m pip3 install pymongo==3.5.1
更新 python3 -m pip3 install --upgrade pymongo
2、链接MongoDB方法
直接传入MongoDB的连接字符串,它以mongodb开头
client = MongoClient('mongodb://localhost:27017/')
连接MongoDB数据库
client = pymongo.MongoClient(host='XXXXXXXXXXX',
port=27017,
username='root',
pwd='XXXXXXXXXXXX')
3、指定数据库
指定数据库,连接数据库'my_test',真正插入文档后才会创建
db = client.my_test
或者
db = client['my_test']
4、指定集合
指定集合(例如:指定一个集合名称为students)
collection = db.students
或者
collection = db['students']
5、插入数据
python 3 官方已经不推荐使用insert()方法了,有警告,返回的是在执行后返回_id集合。
官方推荐使用:
insert_one() #插入一条数据,返回InsertOneResult对象,调用inserted_id属性,获取_id
insert_many() #插入多条记录,返回InsertOneResult对象,调用inserted_ids属性,获取_id
6、查询
6.1 find_one()---查询单个结果
# 查询name为Mike的数据,它的返回结果是字典类型
result = collection.find_one({"name": "Mike"})
print(result) # 结果中_id属性,MongoDB在插入过程中自动添加的
6.2 find()---查询多条数据,返回一个生成器对象
results = collection.find({"age": 20})
for i in results:
print(i)
6.3 通过ObjectId来查询,此时需要使用bson库里面的objectid
# from bson.objectid import ObjectId
#
# result_id = collection.find_one({'_id': ObjectId('61234301f091fa942b77db7f')})
# print(result_id)
6.4比较符号归纳
符号含义示例:
$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]}}
6.5正则匹配$regex
符号含义示例示例含义:
$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字符串
$where高级条件查询{'$where': 'obj.fans_count == obj.follows_count'}自身粉丝数等于关注数
7、计数
# 不带有条件计数
count = collection.estimated_document_count()
print(count)
# 带有查询条件计数
count1 = collection.count_documents({'age': 20})
print(f"age = 20的一共 {count1} 条数据")
8、排序
直接调用sort()方法,并在其中传入排序的字段及升降序标志即可
results = collection.find().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])
pymongo.ASCENDING------升序,1
pymongo.DESCENDING-----降序,-1
9、更新
update_one() # 更新一条
update_many instead() # 更新多条
condition = {'name': 'Mike'}
student = collection.find_one(condition)
student['age'] = 22
result = collection.update_one(condition, {'$set': student})
print(type(result))
print(f"匹配的数据条数:{result.matched_count}, 影响的数据条数是:{result.modified_count}")
# 在这里调用了update_one方法,第二个参数不能再直接传入修改后的字典,而是需要使用{'$set': student}这样的形式,
# 其返回结果是UpdateResult类型,然后调用matched_count和modified_count属性分别可以获得匹配的数据条数和影响的数据条数。
10、删除
delete_one()即删除第一条符合条件的数据,
delete_many()即删除所有符合条件的数据。
它们的返回结果都是DeleteResult类型,可以调用deleted_count属性获取删除的数据条数
result = collection.delete_one({'name': 'Mike'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age': {'$lt': 25}})
print(result.deleted_count)