从<db-name.bson>恢复插入太大时,MongoDB可以转储但不能存储"错误

人气:964 发布:2022-10-16 标签: mongodb size document dump store

问题描述

我在我的一个客户数据库中遇到了一个问题,有一个文档膨胀到16MB,达到了MongoDB;最大文档大小的限制:https://docs.mongodb.com/manual/reference/limits/

为了调试它,我使用mongodump命令转储了数据库,该命令为我的数据库创建了bson文件。 我尝试使用mongorestore命令将转储的数据库重新加载到我的机器上的mongo,但我发现错误:

Failed: Data.events: error restoring from /dbimport/Data/events.bson: an inserted document is too large
我怎么可能不能重新加载转储的数据库? 我认为这可能是因为文档的大小非常接近";最大限制(16MB),但没有超过它,所以它在我的数据库中,但在尝试使用mongostore命令导入此文档时,它太接近";最大限制,因此mongo拒绝将其插入到数据库中。

在此方案中,是否有使mongostore命令成功的选项?

推荐答案

我的解决方案是手动打开BSON文件(使用PYTHON),找到大文档并移除其中的一部分,然后将BSON对象写入新的BSON文件并加载编辑后的BSON文件,该文件已成功存储到Mongo。

这没有实现我的愿望,即能够将转储的数据库加载到系统而不进行更改!

Python3:

import bson
from pprint import pprint

def get_bson_data(filename):
    with open(filename, "rb") as f:
        data = bson.decode_all(f.read())

    return data


def report_problematics_documents(data):
    problematics = []

    for item in data:
        if is_too_big(item):
            print(item)input("give me some more...")
            input("give me some more...")
            problematics.append(item)

    print(f"data len: {len(data)}")
    print(f"problematics: {problematics}")
    print(f"problematics len: {len(problematics)}")
        

def shrink_data(data):
    for i,  item in enumerate(data):
        if is_too_big(item):
            data[i] = shrink_item(item) # or delete it...
            print(f"item shrinked: {i}")


def write_bson_file(data, filename):
    new_filename = filename
    with open(new_filename, "wb") as f:
        for event in data:
            bson_data = bson.BSON.encode(event)
            f.write(bson_data)

def is_too_big(item):
    # you need to implement this one...
    pass


def shrink_item(item):
    # you need to implement this one...
    pass


def main():
    bson_file_name = "/path/to/file.bson"
    data = get_bson_data(bson_file_name)
    report_problematics_documents(data)

    shrink_data(data)
    report_problematics_documents(data)

    new_filename = bson_file_name + ".new"
    write_bson_file(data, new_filename)
    
    print("Load new data")
    data = get_bson_data(new_filename)
    report_problematics_documents(data)

if __name__ == '__main__':
    main()

562