17

I am getting multiple similar JSON object from a remote site and looking to store them in a local MongoDB.

What would be the best way to do this ? (Preferably via Mongoid or Mongo-mapper gems)

Thanks

3 Answers 3

29

You can use a mongoid field of type Hash or an embedded document.

class MyModel
  include Mongoid::Document
  field :some_data, :type => Hash
end
1
  • For latest releases: field :some_data, type: Hash Commented Jul 19, 2017 at 21:31
12

If you just want store your JSON in Mongo you don't need Mongoid or MongoMapper. Just use the Mongo-ruby-driver

require 'mongo'

db   = Mongo::Connection.new.db('sample-db')
coll = db.collection('test')
coll.insert(ActiveSupport::JSON.decode(you_json))

With that you store in database sample-db in collection test

1

Found out I can just put data directly into mongoid without defining the fields:

SomeMongoidObject['dynamic_attribute'] = json_data

3
  • Nice workaround, but I would still like to see mongoid supporting JSON fields as an option. Commented Jan 17, 2012 at 12:37
  • I have logged this as an issue on GitHub: github.com/mongoid/mongoid/issues/1603 Commented Jan 17, 2012 at 12:49
  • Got feedback on the issue. Apparently you can just use field type Hash or embedded document. Have posted an answer as such here. Commented Jan 18, 2012 at 8:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.