pymongo + redis 实现 "_id" 的自增

由于mongo 没有像mysql 一样的自增字段来最为主键id,这里利用redis hash里的 hincrby 方法实现,mongo的"_id" 能够像mysql一样用正整数唯一且自增:

1.redis 的连接池
# 连接池
# 把他做成单例,写在一个文件里面,import它
import redis
import os
import sys

curPath=os.path.abspath(os.path.dirname(__file__))
rootPath=os.path.split(curPath)[0]
sys.path.append(os.path.split(rootPath)[0])

# 拿到一个redis的连接池
from config import REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_PASSWORD

Redis_Pool=redis.ConnectionPool(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB,password=REDIS_PASSWORD, max_connections=10)
2. 实现自增"_id"
from redis import StrictRedis
from db.Redis_pool import Redis_Pool
redis_url=StrictRedis(connection_pool=Redis_Pool)
 # 主键id,自增id 利用hash的hincrby来实现自增id
metroinfo ={}
inc_num=redis_url.hincrby("inc_num", "a", )   # 每次返回一个整数,逐渐增加1
print(inc_num)
metroinfo["_id"]=inc_num
print(metroinfo)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值