Mongo数据库的使用教程(完全版)
MongoDB是由C++语言编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,其内容存储形式类似JSON对象,它的字段值可以包含其他文档、数组及文档数组,非常灵活。
目录
连接MongoDB
指定数据库与集合
插入数据
查询
计数
排序
偏移
更新
删除
连接MongoDB
import pymongo
client = pymongo.MongoClient(host="localhost",port=27017) #默认的端口号是27017,可以根据需求进行更改
指定数据库与集合
db = client.test # 或: db = client['test'] 这里如果没有该数据库,会自动地进行新建
collection = db.first # 或: db = client['first'] 这里如果没有该集合,会自动地进行新建
插入数据
- insert_one(): 插入一条数据
- insert_many(): 插入多条数据
# #插入数据_一条
student = {
'id':'001',
'name':'小红',
'age':20,
'gender':'male'
}
result = collection.insert_one(student)
print(result) #返回的是InsertOneResult对象
print(result.inserted_id) #我们可以调用其inserted_id属性获取_id,这个_id是mongo自动赋给的
<pymongo.results.InsertOneResult object at 0x000002030178B380>
60fff91cbc6eb6620e54a6b7
#插入数据_多条
student1 ={
'id':'002',
'name':'小明',
'age':20,
'gender':'man'
}
student2 ={
'id':'003',
'name':'小刚',
'age':20,
'gender':'man'
}
result1 = collection.insert_many([student1,student2])
print(result1)
print(result1.inserted_ids)
<pymongo.results.InsertManyResult object at 0x0000020302213880>
[ObjectId('60fff963bc6eb6620e54a6b8'), ObjectId('60fff963bc6eb6620e54a6b9')]
查询
这里我们可以使用find_one()或find()方法进行查询
- find_one() :返回单个结果
- find() : 返回一个生成器对象
我们也可以限制条件进行查询
result2 = collection.find_one({'name':'小红'})
print(type(result2))
print(result2)
<class 'dict'>
{'_id': ObjectId('60fff91cbc6eb6620e54a6b7'), 'id': '001', 'name': '小红', 'age': 20, 'gender': 'male'}
results = collection.find({'age':20})
print(results) # 返回值是cursor类型,它相当于一个生成器,我们可以遍历得到所有结果
for result in results:
print(result)
<pymongo.cursor.Cursor object at 0x000002030221E6A0>
{'_id': ObjectId('60fff91cbc6eb6620e54a6b7'), 'id': '001', 'name': '小红', 'age': 20, 'gender': 'male'}
{'_id': ObjectId('60fff963bc6eb6620e54a6b8'), 'id': '002', 'name': '小明', 'age': 20, 'gender': 'man'}
{'_id': ObjectId('60fff963bc6eb6620e54a6b9'), 'id': '003', 'name': '小刚', 'age': 20, 'gender': 'man'}
# 条件查询
# 如果要查询大于年龄值大于20的
results = collection.find({'age':{'$gt':20}})
# 也可以正则表达式进行查询
results = collection.find({'name':{'$regex':'^小.*'}})
print(results)
for result in results:
print(result)
<pymongo.cursor.Cursor object at 0x000002030221E8B0>
{'_id': ObjectId('60fff91cbc6eb6620e54a6b7'), 'id': '001', 'name': '小红', 'age': 20, 'gender': 'male'}
{'_id': ObjectId('60fff963bc6eb6620e54a6b8'), 'id': '002', 'name': '小明', 'age': 20, 'gender': 'man'}
{'_id': ObjectId('60fff963bc6eb6620e54a6b9'), 'id': '003', 'name': '小刚', 'age': 20, 'gender': 'man'}
这里我总结了一下查询匹配的比较符号和功能符号
比较符号
符号 | 含义 | |
---|---|---|
$lt | 小于 | {‘age’: { ‘$lt’ : 20 } } |
$gt | 大于 | {‘age’: { ‘$gt’ : 20 } } |
$lte | 小于等于 | {‘age’: { ‘$lte’ : 20 } } |
$gte | 大于等于 | {‘age’: { ‘$gte’ : 20 } } |
$ne | 不等于 | {‘age’: { ‘$ne’ : 20 } } |
$in | 在范围内 | {‘age’: { ‘$in’ : [20,22] } } |
$nin | 不在范围内 | {‘age’: { ‘$nin’ : [20,24] } } |
功能符号
符号 | 含义 | 示例 | 示例含义 |
---|---|---|---|
$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 | 文本查询 | {‘KaTeX parse error: Expected '}', got 'EOF' at end of input: text':{'search’:‘Mike’}} | text类型的属性中包含Mike字符串 |
$where | 高级条件查询 | {’$where’:‘odj.fans_count == obj.follows_count’ } | 自身粉丝数等于关注数 |
计数
# # 计数
count = collection.count_documents({'gender':'man'})
print(count)
2
排序
#排序
results = collection.find().sort('id',pymongo.DESCENDING) # pymongo.ASCENDING升序
for result in results:
print(result)
{'_id': ObjectId('60fff963bc6eb6620e54a6b9'), 'id': '003', 'name': '小刚', 'age': 20, 'gender': 'man'}
{'_id': ObjectId('60fff963bc6eb6620e54a6b8'), 'id': '002', 'name': '小明', 'age': 20, 'gender': 'man'}
{'_id': ObjectId('60fff91cbc6eb6620e54a6b7'), 'id': '001', 'name': '小红', 'age': 20, 'gender': 'male'}
偏移
在某些情况下,我们可能想只取某几个元素,这时可以利用skip()方法偏移几个位置,比如偏移2,就忽略前两个元素,得到第三个及以后的元素:
#取数(偏移,限制)
# skip() : 偏移个数
# limit() : 指定要取的结果个数
results = collection.find().skip(1).limit(1)
for result in results:
print(result)
{'_id': ObjectId('60fff963bc6eb6620e54a6b8'), 'id': '002', 'name': '小明', 'age': 20, 'gender': 'man'}
更新
- update_one(): 更新一条数据
- update_many(): 更新多条数据
#更新
# update_one()
condition = {'name':'小红'}
student = collection.find_one(condition)
student['name'] = '小丽'
result = collection.update_one(condition,{'$set':student}) # 使用$set操作符对数据进行更新
print(result)
print(result.matched_count,result.modified_count) # 获得匹配的个数和影响的个数
<pymongo.results.UpdateResult object at 0x0000020302231A80>
1 1
#update_many()
condition = {'age':20}
result = collection.update_many(condition,{'$inc':{'age':1}}) #$inc 加一操作
print(result)
print(result.matched_count,result.modified_count) # 获得匹配的个数和影响的个数
<pymongo.results.UpdateResult object at 0x0000020302231100>
3 3
删除
- delete_one: 删除一条数据
- delete_many: 删除多条数据
#删除一条数据
result = collection.delete_one({'name':'小明'})
print(result)
print(result.deleted_count) #获得删除的个数
<pymongo.results.DeleteResult object at 0x000002030222C780>
1
#删除多条数据
result = collection.delete_many({'age':21})
print(result)
print(result.deleted_count) #获得删除的个数
<pymongo.results.DeleteResult object at 0x00000203021FEF80>
2