2016-09-01 4 views
3

mongoリストアを介してファイルをdbにインポートせずに、mongodb bsonファイルに格納されている文書の数を計算したいと思います。素早くbson文書内のオブジェクトの数を数えます

私は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

+0

されています

だから、私は信じて、この関数はトリックを行う必要がありますあなたは使っていますか?これはmongodb bsonか別のものですか? – 16num

+0

はこの情報で質問を更新しました。私が使用しているbsonパッケージは、以下のhttps://api.mongodb.com/python/current/api/bson/index.html – user1438162

答えて

2

手作りのファイルはありませんが、手でデータを解析する方法があると思います。

source for bson.decode_file_iter(サンセリフのdocstring)はこのように書きます:私は推測

_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呼び出しです - あなたは1を必要としません。

したがって、ファイルを読み取るだけで、次のドキュメントのサイズでint32値を取得してスキップするだけで済みます。次に、これを実行した文書の数を数えます。パッケージをBSON

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を持っていない。。)

+0

です。あなたの関数に加えて、 'import struct'はhttps://docs.python .org/2/library/struct.html# – user1438162

+0

はい、さらにいくつかのインポート( 'os.SEEK_CUR'と' InvalidBSON'例外)があります。私は答えを編集しました。 – drdaeman

+0

@ user1438162 'struct.Struct(" drdaeman

関連する問題