meow
meow

Reputation: 28174

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}] )

Upvotes: 7

Views: 2647

Answers (3)

Sheharyar
Sheharyar

Reputation: 75820

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.

Upvotes: 4

mvj3
mvj3

Reputation: 21

Just use MongoidModel.create directly.

Upvotes: 0

bowsersenior
bowsersenior

Reputation: 12574

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)

Upvotes: 8

Related Questions