Question

I've been going all over the web looking for a solution to my problem. I' m using Mongoid to write a set of data to MongoDB.

I'm trying to do a batch insert with mongoid as follows:

class Geonode
  include Mongoid::Document
  include Mongoid::Timestamps

  embeds_one :location
  embeds_one :transport

end

class Location
  include Mongoid::Document

  field :city,        :type => String

  embedded_in :geonode

end

class Transport
  include Mongoid::Document

  embeds_many :trainstation
  embedded_in :geonode

end

class Trainstation
  include Mongoid::Document

  field :station, :type => String

  belongs_to :transport

end

And it works fine to do it one by one, but if i want to batch a lot of them, what do i do?

i tried.

require 'moped'
require 'rubygems'
require 'mongo'
require 'mongoid'

require 'skySchema.rb' #schema is the file i defined the classes just before



Mongoid.load!("./mongoid.yml", :development)

include Mongo

batch = []

batch << {:location => Location.new(:city => "London"),
          :transport => Transport.new(:trainstation => 
           [Trainstation.new(:station => "Kings Cross")])}}

and then doing this many many times, after which 

Geonode.collection.insert(batch)

but it doesn't work. Am i doing something wrong?

Was it helpful?

Solution

The issue was that for batch insertion, you needed to do :

Geonode.insert(batch)

And format the batch in a different way. All is cool now. Thanks for the help guys.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top