Rails: Store JSON in MongoDB
Asked Answered
H

3

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

Hilton answered 30/10, 2010 at 10:52 Comment(0)
N
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
Nether answered 18/1, 2012 at 8:44 Comment(1)
For latest releases: field :some_data, type: HashHistoried
N
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

Nightwear answered 30/10, 2010 at 11:24 Comment(0)
H
1

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

SomeMongoidObject['dynamic_attribute'] = json_data

Hilton answered 17/11, 2010 at 9:22 Comment(3)
Nice workaround, but I would still like to see mongoid supporting JSON fields as an option.Nether
I have logged this as an issue on GitHub: github.com/mongoid/mongoid/issues/1603Nether
Got feedback on the issue. Apparently you can just use field type Hash or embedded document. Have posted an answer as such here.Nether

© 2022 - 2024 — McMap. All rights reserved.