开发者

MongoDB's BSON gem can't read a MongoDB database file?

I have a MongoDB DB with some data. That all works fine, the data was inserted into the mongo DB properly. What I want to do now, though, is open the mongoDB DB file, and parse it using the BSON gem so that I can look at the human-friendly format of the mongo DB file.

data = nil

File.open("input/bson/database_development.0") do |f|
  data = f.read
end

unpacked_data = BSON.deserialize(data)

File.new("input/bson/output.txt", "w") do |f|
  f.write(unpacked_data)
end

However, this gives me the following error:

/home/user/.rvm/gems/ruby-1.9.2-p180/gems/bson-1.3.1/lib/bson/bson_c.rb:28:in `deserialize': no c decoder for this type yet (-86) (TypeError)
from /home/user/.rvm/gems/ruby-1.9.2-p180/gems/bson-1.3.1/lib/bson/bson_c.rb:28:in `deserialize'
from /home/user/.rvm/gems/ruby-1.9.2-p180/gems/bson-1.3.1/lib/bson.rb:37:in `deserialize'
from bsoner.rb:16:in `&开发者_开发问答lt;main>'

From google a little bit, some folks said that mongoDB can ACCEPT any kind of input and store it, but can't READ just any kind of data. So they're saying that the database file has bad data in it that can't be read properly. But shouldn't it be able to read anything that it can insert?


Adding to Emily's answer: there are some utilities that you can use to examine the files directly. First, dump the database using mongodump:

mongodump

That will dump the data files to raw BSON.

Then you can examine the bson with bsondump:

bsondump dump/test/foo.bson

There's also a Ruby utility that ships with the gem:

b2json dump/test/foo.bson


MongoDB is not a file-based database. In order to read the data back out, you need to connect to the running MongoDB server. The BSON gem is for parsing the data returned by the server, not parsing the files themselves.

To connect to your MongoDB server and read data, you'll do something like the following:

require 'rubygems'
require 'mongo'

connection = Mongo::Connection.new # connects to localhost by default
db   = connection['sample-db']
collection = db['test']

outfile = File.open('output.txt', 'w')
collection.find.each { |doc| outfile.puts doc.inspect }

The collection and db objects have additional methods that will let you get a list of all databases and collections, if you need to print out the data in all of those as well. Check out the API documentation for the mongo gem for more information.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜