开发者

Ruby datajob with mongoid

I'm trying to use ruby and mongoid in order to extract some data from an oracle database and into my mongoDB in order to perfom a couple of operations on it.

The question is:

I created my 'Record' class with includes the Mongoid::Document and set up all开发者_Python百科 my fields, and have already assigned the data coming out of the oracle database, and have all my BSON objects stored in an array.

Now my question is: How I save them?

Here's my piece of code

query = db.report # Sequel Object

query.each do |row|
  r = Record.new #Mongoid class
  r.directory_name    = row[:directory_name]
  r.directory_code    = row[:directory_id]
  r.directory_edition = row[:edition]
  r.last_updated      = row[:updated]
  r.canvass           = row[:canvass_id]
  r.specialty_item    = row[:item]
  r.production_number = row[:prodnr]
  r.status            = row[:exposure_status]
  r.scanned_date      = row[:scandate]
  r.customer_id       = row[:customer_id]
  r.sales_rep         = row[:sales_rep_name]
  r.phone             = row[:phone]
  r.customer_name     = row[:customer_name]
  records << r
end


You would need to do Record.collection.insert(records). Although note that this will skip any validations you have written in your Mongoid model but will be a little faster than creating mongoid records and saving them, as it will use the ruby mongo driver directly. You should only do this if you know that data is consistent.

If you want to do all the validations on your data before saving them in MongoDB, you should create a model instead of putting them in an array.

So you can persist the data extracted in MongoDB in three ways according to your preferences:

  • Insert all records at once using mongo driver, but beware the array you are creating can be huge:
query.each do |row|
  .....
end
Record.collection.insert(records)
  • Insert one record at a time using mongo driver(replace records << r with new line)
query.each do |row|
  .....
  Record.collection.insert(r)
end
  • Insert one record at a time using Mongoid and all the validations and callbacks(replace records << r with new line)
query.each do |row|
  .....
  r.save
end


update: Missed that you are already creating the record hence the mongo driver suggestions. If you want to use mongo driver directly, you should use a hash instead of Mongoid model. i.e instead of

r = Record.new
r.status = row[:status]
# copy more data

you should do

r = {}
r[:status] = row[:status]
# copy more data
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜