Boris
Boris

Reputation: 3243

Rails: Store JSON in MongoDB

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

Upvotes: 17

Views: 9711

Answers (3)

mydoghasworms
mydoghasworms

Reputation: 18613

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

class MyModel
  include Mongoid::Document
  field :some_data, :type => Hash
end

Upvotes: 29

Boris
Boris

Reputation: 3243

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

SomeMongoidObject['dynamic_attribute'] = json_data

Upvotes: 1

shingara
shingara

Reputation: 46914

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

Upvotes: 12

Related Questions