首页 > 解决方案 > 使用 python 脚本切换集合

问题描述

我目前正在编写一个数据迁移脚本,并在脚本的函数中调用以下行:

output_file.write(process_input_row(row, custom_field_map, args.entry_type, args.entry_prefix, args.book_name))

在对 process_input_row 的调用中,我将数据插入到它默认定位的当前集合中。我想要做的是调用标准的“使用 Collection_Name”,您通常会从 python 脚本中的 mongo shell 调用它,以便将数据插入到正确的集合中。

这样做最简单的方法是什么?我可以将“从子流程导入调用”添加到我的文件顶部并执行类似“调用('use Collection_Name')”之类的操作吗?见下文:

with open(args.entries_file, newline='') as csv_input_file, open(args.output_file, 'w') as output_file:
    reader = csv.reader(csv_input_file, delimiter=',', quotechar='"')
    row_counter = 0
    max_id = 0
    for row in reader:
        if int(row[1]) > max_id:
            max_id = int(row[0])
        output_file.write(process_input_row(row, custom_field_map, args.entry_type, args.entry_prefix, args.book_name))
        row_counter = row_counter + 1
    max_id += 1

    # Switch to different collection here
    call('use Collection_Name')

提前致谢!

标签: pythondatabasemongodbshellcollections

解决方案


推荐阅读