Python basic tutorial to operate NoSQL database

Non-relational database

1. Operate the Redis database

Download and install redis related libraries

$ pip install redis

Connect to the database example

import redis

client = redis.Redis(host='127.0.0.1',port=6379,password='')

# 清空操作
client.flushdb()
client.flushAll()

String type data

import redis

client = redis.Redis(host='127.0.0.1',port=6379,password='')

client.set('name','张三')
client.get('name')
client.mset({'k1':'value1','k2':'value2'})
client.mget(['k1','k2'])

Hash type data

import redis

client = redis.Redis(host='127.0.0.1',port=6379,password='')

client.hset('student','{}')
client.hget('student','name')
client.hgetall('student')

List type data

import redis

client = redis.Redis(host='127.0.0.1',port=6379,password='')

client.lpush('name','zhangsan')
client.lpush('name','lisi')
client.llen('name')
client.lpop('name')

Set type data

import redis

client = redis.Redis(host='127.0.0.1',port=6379,password='')

client.sadd('zhangsan','lisi')
client.scard('zhangsan')
client.spop('zhangsan')

ZSet type data

import redis

client = redis.Redis(host='127.0.0.1',port=6379,password='')

client.zadd('student',{'stu1':'zhangsan','stu2':'lisi'})
client.zcard('student')
client.zcount('student', 1, 2)
client.zrange('student', start=0, end=2)

2. Operate the MongoDB database

Term correspondence

Insert picture description here

Download and install mongodb database

sudo yum install epel-release.noarch

# 如果失败执行上面
sudo yum install mongodb-server -y
sudo yum install mongodb -y

# 启动服务
mongod -f /etc/mongod.conf

# 启动客户端
mongo

Command line related operations

# 展示数据库
show databases;

# 创建、删除数据库
use newdatabase;
db.dropDatabase()

# 创建表、展示表、删除表
db.createCollection('student')
db.createCollection('teacher')
show collections;
db.student.drop()

# 数据的增删改查
db.student.insert({'name':'zhangsan','age':20})
db.student.update({'name':'zhangsan'},{'name':'lisi','age':21})
db.student.remove({'name':'zhangsan'})
db.student.find()
db.student.find().pretty()

Download and install mongodb related libraries

$ pip3 install pymongo

Code related operations

from pymongo import MongoClient

# 创建连接对象
client = MongoClient(host='localhost',port=27017)

# 获取数据库对象
db = client.newdatabase

# 获取指定数据表的操作游标
cursor = db.student

# 进行增删改查操作
cursor.insert({"name":"zhangsan","age":18})
cursor.save({"name":"zhangsan","age":18})
cursor.update({"name":"zhangsan"},{'$set':{"age":20}})
cursor.remove({'name': 'zhangsan'})
cursor.remove()

# 遍历查询操作
for stu in cursor.find()
	print(stu)
	
cursor.find_one({'name':'zhangsan'})