python 非关系型数据库MongoDB存储的简单操作示例

# 使用MongoClient来链接mongodb,第二个参数port不传递参数时默认为27017
import pymongo
client = pymongo.MongoClient(host='localhost',port = 27017)
# 指定要使用的数据库
db = client.test
# 数据库中有许多集合,类似于关系型数据库的表,指定要操作的集合
collection = db.students
# 新建数据要以字典的形式
student = {
    'id':'3421552',
    'name':'bob',
    'age':20,
    'gender':'male'
}

# 插入数据
# 调用insert方法直接插入数据,但是pymongo3不推荐使用了
# result = collection.insert(student)
# 官方推荐的是insert_one和insert_many来插入一条或者多条记录,插入多条数据时,要以列表的形式传递
result = collection.insert_one(student)
print(result)
# 在mongo中,每条数据都有唯一一个ID属性来标识
print(result.inserted_id)

# 查询
# find_one查询得到的是单个结果,find方法则返回一个生成对象。返回结果都会多出_id属性,这是插入过程自动生成的
result1 = collection.find_one({'name':'mike'})
print(type(result1))
print(result1)

# 查询大于年龄20的数据,条件键值是一个字典,键名为比较符号$gt
'''
$gt大于
$lt小于
$gte大于等于
$lte小于等于
$ne不等于
$in在范围内
$nin不在范围内
'''
result2 = collection.find({'age':{'$gt':20}})
# 也可以进行正则匹配,$regex指定正则匹配
'''
$regex匹配正则表达式
$exists属性是否存在
$type类型判断
$mod数字模操作
$text文本查询
$where高级条件查询
'''
result3 = collection.find({'name':{'$regex':'^M.*'}})
# count()统计查询结果又多少条数据
count = collection.find().count()
print(count)

# 排序
# sort()用于排序,pymongo.ASCENDING表示升序,pymongo.DESCENDING表示降序
result4 = collection.find().sort('name',pymongo.ASCENDING)
print(result['name'] for result in result4)

# 偏移
# skip(2)表示忽略前两个元素,数据量非常庞大时,不要使用大的偏移,否则会溢出内存
result5 = collection.find().sort('name',pymongo.ASCENDING).skip(2)
print(result['name'] for result in result5)

# limit(2)表示指定要取的结果个数
result6 = collection.find().sort('name',pymongo.ASCENDING).skip(2).limit(2)
print(result['name'] for result in result6)

# 更新
# 官方推荐使用的是update_one与update_many,第二个参数需要使用$类型操作符作为字典的键名
condition = {'name':'kevin'}
student = collection.find_one(condition)
student['age'] = 24
# result7 = collection.update(condition,student)
result7 = collection.update_one(condition,{'$set',student})
print(result7)
# result7.matched_count获得匹配的数据条数,result7.modified_count获得影响的数据条数
print(result7.matched_count,result7.modified_count)

# 删除
# remove()指定删除的条件,符合的都会被删除。delete_one与delete_many
result8 = collection.delete_one({'name':'kevin'})
print(result8)
print(result8.deleted_count)
result9 = collection.delete_many({'age':{'$lt':25}})
print(result9.deleted_count)

猜你喜欢

转载自blog.csdn.net/weixin_41931602/article/details/82734502