Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid: Creating many objects with a single call

I have 1000 users that i will be retrieving from Twitter, and I would like to save them at one shot, as opposed to doing 1000 insertions individually.

How can I do this on Mongoid? Something like this would rock:

TwitterUser.createMany([{:name=>u1}, {:name=>u2},{:name=>u3}] )
like image 579
meow Avatar asked Dec 07 '10 10:12

meow


2 Answers

You should use the Mongo ruby driver to do this. You can pass an array of hashes to the insert method to create multiple documents at once (more info on this google groups discussion). Mongoid makes it easy to access the ruby driver.

The code would look something like this:

user_list = twitter_accounts.map do |account|
  # create a hash of all the fields to be stored in each document
  { 'name' => account.name, 
    'username' => account.username 
    # some other fields...
  }
end

Mongoid.master['twitter_users'].insert(user_list)
like image 151
bowsersenior Avatar answered Oct 16 '22 12:10

bowsersenior


You almost got it, it's create, not createMany. You can use it like this:

TwitterUser.create([
  { username: "u1", display_name: "Display Name 1" },
  { username: "u2", display_name: "Display Name 2" },
  { username: "u3", display_name: "Display Name 3" }
])

Also, as @bowsersenior points out, it's a good idea to use it with Array#Map:

TwitterUser.create(
    @users_array.map do |u|
        { username: u.username, display_name: u.name }
    end
)

From the Mongoid#Persistence Docs:

Model.create

Insert a document or multiple documents into the database

Model.create!

Insert a document or multiple documents into the database, raising an error if a validation error occurs.

like image 39
Sheharyar Avatar answered Oct 16 '22 11:10

Sheharyar