Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 快速计算bson文档中的对象数_Python_Mongodb_Bson - Fatal编程技术网

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

Python 快速计算bson文档中的对象数,python,mongodb,bson,Python,Mongodb,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文档中的文档数而不进行完全解码 我

我想计算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文档中的文档数而不进行完全解码

我目前正在使用Python2.7和pymongo。

我手头没有文件可供尝试,但我相信有一种方法——如果您手动解析数据

(无文档字符串)如下所示:

_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)

(不过我还没有测试代码。手头没有MongoDB。)

您使用的是哪个bson包?这是mongodb bson还是另一个?使用此信息更新了问题。我正在使用的bson包是对您的函数的以下唯一添加,即“导入结构”-是,再加上一些导入(
os.SEEK\u CUR
invalidson
异常)。我已经编辑了答案。@user1438162如果替换
struct.struct(“
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