首页 > 解决方案 > BSON:Module 的未定义方法“read_bson_document”

问题描述

我正在尝试使用这个 Ruby 脚本:

require "bson"

def make_insert(table_name, bson)
  columns = ["id",*bson["value"].keys] * ", "
  values = ["'#{bson["_id"]}'",*bson["value"].values.map{|value| value.is_a?(Numeric) ? value : "'#{value}'"}] * ", "
  return "insert into #{table_name} (#{columns}) values (#{values});"
end

file_name = ARGV.first
file=File.new(file_name)
table_name=File.basename(file_name,".*")
while not file.eof? do
  bson = BSON.read_bson_document(file)
  STDOUT << make_insert(table_name,bson)
  STDOUT << "\n"
end 

要将数据从 bson 转换为 sql,会引发以下错误: convertbson2sql.rb:13:in <main>': undefined methodread_bson_document' for BSON:Module (NoMethodError)

我认为在新版本的 BSON 库中不再使用 read_bson_document 方法,我在网上和 BSON 库文档中进行了搜索,但找不到替代方法。

PS:我对Ruby几乎一无所知,我只想使用脚本来转换我的数据。

标签: rubyrubygemsbson

解决方案


不是 100% 肯定,但看起来 2.0.0 确实有大规模的变化CHANGE LOG

基于此,您可以尝试以下操作:

require 'bson'
require 'stringio'

stringio = StringIO.new
stringio.write File.read(file_name)
stringio.rewind
bson = BSON::Document.from_bson(stringio)

根据@SergioTulentsev,适当的方式实际上可能是:

bson = BSON::Document.from_bson(BSON::ByteBuffer.new(File.read(file_name)))

但是,这仅在每个文件都是单个BSON::Document.


推荐阅读