首页 MongoDB Mongodb循环整个数据库进行数据处理 mongodb数据库分页读取

Mongodb循环整个数据库进行数据处理 mongodb数据库分页读取

2024-09-13 08:59 编辑:  丽丽学习网

Mongodb循环整个数据库进行数据处理,应用场景,有时候需要对整个数据库进行数据处理,需要读取整个数据库,如果数据量较大,一次性读取则会卡机,所以还是需要分页读取后进行处理,这里写一段分页处理mongodb数据的思路,分享给大家,铭记:方法不是唯一,效果却是一样。技术不是用来炫,最新版本不一定是最好的,稳定才是王道。

import random
from bson.objectid import ObjectId
import pymongo
import re
from common.mongodatahelper import MongoDBHelper
import time
# 设置socket的超时时间,解决一直卡住的问题
import socket
socket.setdefaulttimeout(10)
# 全局变量
password=''
dbname=''
dbper = MongoDBHelper(host='主机名',port=端口,username=dbname,password=password,authsource=dbname,databasename=dbname)
# 开始
    maxid=None
    tablename='search'
    # 循环每个表
    while True:
        contentlist=[]
        if maxid:
            # 存在maxid
            cdtm1=dbper.CurdDataToMongo(content=None,tablename=tablename,myquery={'_id':{'$gt':maxid}},curd='r',limit=100,sort=[('_id',pymongo.ASCENDING)])
            if cdtm1 and cdtm1[0]==0 and type(cdtm1[1])==list and len(cdtm1[1])>0:
                for item1617 in cdtm1[1]:
                    if maxid<item1617['_id']:
                        maxid=item1617['_id']
                contentlist=cdtm1[1]
            else:
                break
        else:
            # 第一次不存在maxid
            cdtm1=dbper.CurdDataToMongo(content=None,tablename=tablename,myquery=None,curd='r',limit=1,sort=[('_id',pymongo.ASCENDING)])
            if cdtm1 and cdtm1[0]==0 and type(cdtm1[1])==list and len(cdtm1[1])>0:
                maxid=cdtm1[1][0]['_id']
                contentlist=cdtm1[1]
            else:
                print('此表无数据,talbename={}'.format(tablename))
             break        
      if contentlist:
             for item1639 in contentlist:
               num+=1
               id=item1639['_id']
               title=item1639['title']