第11讲---- MongoDB在Python中使用和redis的安装与使用
整体课程知识点查看 :https://blog.csdn.net/j1451284189/article/details/128713764
本讲总结
MongoDB与Python交互使用
redis安装与使用
redis简单使用
一、MongoDB与Python交互
# MongoDB 3.4.24
# pymongo 3.2
import pymongo
try:
# 1、链接mongodb的服务
mongo_py = pymongo.MongoClient()
# 2、库和表的名字
# db = mongo_py['ku']
# collection = db['biao']
collection= mongo_py['ku']['biao']
# 3、插入数据
one = {'name':'apple','age':20}
two_many = [
{'name': 'banana', 'age': 20},
{'name': 'city', 'age': 30},
{'name': 'day', 'age': 40},
{'name': 'egg', 'age': 50},
]
# collection.insert_one(one)
# collection.insert(one) #支持一条河多条
# collection.insert_many(two_many)
# collection.delete_one({'age':20})
# collection.delete_many({'age': {'$in': [30, 40]}})
# collection.update_one({'age': 20}, {'$set': {'name': 'zig'}})
# collection.update_many({'age': 20}, {'$set': {'name': 'zig'}})
result = collection.find({'age':20})
print(result[0])
except Exception as err:
print(str(err))
finally:
# 4、关闭数据库
mongo_py.close()
二、redis安装与启动
redis是一个key-value存储系统。数据都是缓存在内存中。周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。
安装教程:下载解压,将解压后的位置加入环境变量 直接运行以下命令即可启动
下载地址:https://github.com/tporadowski/redis/releases
下载地址2(5.0.14):https://blog.csdn.net/daxiang52/article/details/125350003
版本:5.0.14
redis-server.exe #服务端启动
redis-cli.exe #客户端启动
三、redis简单使用
查看配置文件与参数详解:略
"""普用操作"""
lpush one 1 2 3
type one #查看类型 # list
set name 'apple'
keys * # 查询所有键 #name one
flushall # 清空所有数据库的键值对
select 14 # 切换至数据库14 默认为数据库0 (共有16个数据库0-15)
"""字符串的操作"""
# 设置键值对
set name 'apple' #单次写入 设置键值对
setex age 5 18 #设置到期过期的键值对 5S后该键值对消失
mset one 1 two 2 three 3 #单次写入 设置键值对
# 获取对应键的值
get name # 获取键name 的值
mget one two three # 获取多个键对应的值
#修改
append two 3456 #在对应键的值后添加内容 #23456
"""hash对象的操作"""
hset person name jenny age 18 #设置对象person的属性 name 和age
hkeys person # 查看对象person的属性
hvals person # 查看对象person的所有属性的值
hget person name #获取对象person 的属性 name的值
hdel person name #删除对象person的name属性及值
"""list的操作"""
lpush one 1 #向列表one中添加数据(左) # 1
lpush one 2 3 4 5 6 #向列表one中添加数据(左) # 6 5 4 3 2 1
rpush two 1 2 3 4 5 6 #向列表one中添加数据(右) # 1 2 3 4 5 6
lrange one 0 -1 #查看列表中的数据 从头到尾
#数据pop
lpop one #取出并删除 6 # 5 4 3 2 1
rpop one #取出并删除 1 # 5 4 3 2
#数据插入
linsert two before 4 a # 在4之前插入a # 1 2 3 a 4 5 6
linsert two after 6 b #在6之后插入b # 1 2 3 a 4 5 6 b
linsert two before 1 a #在1之前插入a # a 1 2 3 a 4 5 6 b
#数据设置
lset two 0 A # 设置下标0的值为A # A 1 2 3 a 4 5 6 b
#数据删除
rpush num 1 2 3 4 5 6 5 4 3 # 1 2 3 4 5 6 5 4 3
lrem num 1 2 # 删除数组two中左数的第一个的值4 # 1 2 3 5 6 5 4 3
lrem num -1 5 # 删除数组two中右数的第一个的值5 # 1 2 3 5 6 4 3
lrem two 0 3 #删除数组two中所有的值3 # 1 2 5 6 4