微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python-快速计算bson文档中的对象数

我想计算存储在mongodb bson文件中的文档数,而不必通过mongo restore将文件导入到db中.

我能够在python中提出的最好的方法

bson_doc = open('./archive.bson','rb')
it = bson.decode_file_iter(bson_doc)
total = sum(1 for _ in it)
print(total)

从理论上讲,这是可行的,但是当bson文档很大时,在实践中就很慢.任何人都可以在不进行完整解码的情况下更快地计算bson文档中文档的数量

我目前正在使用python 2.7和pymongo.
https://api.mongodb.com/python/current/api/bson/index.html

解决方法:

我没有手头的文件,但我相信有办法-如果您要手动解析数据.

source for bson.decode_file_iter(没有文档字符串)如下所示:

_UNPACK_INT = struct.Struct("<i").unpack

def decode_file_iter(file_obj, codec_options=DEFAULT_CODEC_OPTIONS):
    while True:
        # Read size of next object.
        size_data = file_obj.read(4)
        if len(size_data) == 0:
            break  # Finished with file normaly.
        elif len(size_data) != 4:
            raise InvalidBSON("cut off in middle of objsize")
        obj_size = _UNPACK_INT(size_data)[0] - 4
        elements = size_data + file_obj.read(obj_size)
        yield _bson_to_dict(elements, codec_options)

我想,耗时的操作是_bson_to_dict调用-您不需要一个.

因此,您所需要做的就是读取文件-获取具有下一个文档大小的int32值并跳过它.然后计算执行此操作时遇到的文档数.

因此,我相信,此功能应该可以解决问题:

import struct
import os
from bson.errors import InvalidBSON

def count_file_documents(file_obj):
    """Counts how many documents provided BSON file contains"""
    cnt = 0
    while True:
        # Read size of next object.
        size_data = file_obj.read(4)
        if len(size_data) == 0:
            break  # Finished with file normaly.
        elif len(size_data) != 4:
            raise InvalidBSON("cut off in middle of objsize")
        obj_size = struct.Struct("<i").unpack(size_data)[0] - 4
        # Skip the next obj_size bytes
        file_obj.seek(obj_size, os.SEEK_CUR)
        cnt += 1
    return cnt

(不过,我尚未测试过代码.手头没有MongoDB.)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐