Python 使用正则表达式进行MongoDB条件查询

一、统计

db.VideoProfile.find( {_id: { $regex: /^1_[0-9]{5,}$/} } ).count()

其中正则表达式为 /^1_[0-9]{5,}$/

/^正则开始符号,$/正则结束标记

1_表示以此为开始

[0-9]代表数字

{5,}表示前面的数字至少出现5次,无上限

二、Python 代码

def extract_qq(batch_num, platform, profile_collection, path):
    """
    :param path: qq号导出文件路径
    :param platform: 平台
    :param profile_collection: 数据库集合
    :type batch_num: int
    """
    qq_file = open(path, 'w')
    key = "name" if platform == "PAC" else "_id"
    cnt = profile_collection.count({key: {"$regex": "1_[0-9]{5,}"}})
    print("cnt = %d" % cnt)
    length = int(math.ceil(cnt / float(batch_num)))
    # 数据库查询QQ号,导出到本地文件
    for x in xrange(0, length):
        print("%d/%d" % (x, length))
        cursor = profile_collection.find({key: {"$regex": "1_[0-9]{5,}"}}, {key: 1}).limit(batch_num).skip(x*batch_num)
        for user_profile in cursor:
            qq_file.write(user_profile.get(key).split("1_")[1] + "\n")
        cursor.close()
    qq_file.close()

因为库里数据量较大,需要分批次读取,使用limit和skip函数可以实现该功能,skip表示从第几行开始读取,limit表示一次读取多少量

由于只要提取Key字段,所以查询条件{key:1}, 其他字段不必查询,这样可以降低空间复杂度

猜你喜欢

转载自blog.csdn.net/jxq0816/article/details/81103394