2

I have an array of hashes like this:

[
  {
    id: 123,
    color: 'red'
  },
  {
    id: 456,
    color: 'green'
  }
]

I know how to fetch and update one at a time:

params[:my_documents].each do |doc|
  MyDocument.find(doc[:id]).update_attributes(color: doc[:color])
end

…but I suspect that the performance is not very good. I'd like to find a way where I can pass the data to Mongoid/MongoDB directly so that I can update each document without having to find and instantiate every document in order to update a few fields.

How can I perform a batch update using Mongoid without having to fetch them first?

Andrew
  • 227,796
  • 193
  • 515
  • 708
  • No, the point is that I know the `id` of all the documents I want to update, and I need to update multiple documents, so I want to find a way to pass the data and have it perform as one efficient transaction rather than sequentially fetching and updating one document at a time. – Andrew Mar 06 '14 at 01:17
  • Is there some reason this is not a duplicate? You seem to be saying you already know all the data you want to insert. http://stackoverflow.com/questions/3772378/batch-insert-update-using-mongoid – Neil Lunn Mar 06 '14 at 02:26
  • Actually nope it isn't your talking about updates – Neil Lunn Mar 06 '14 at 02:28
  • Not really an answer, but wait for the 2.6 release: http://docs.mongodb.org/master/reference/command/update/#dbcmd.update – Neil Lunn Mar 06 '14 at 02:33

1 Answers1

1

The mongo-ruby-driver version 1.10 (gem 'mongo', '~> 1.10.0') supports bulk write operations. For your example, a batch of updates can be submitted as one request for significant performance gains when used with a 2.6 MongoDB server.

https://github.com/mongodb/mongo-ruby-driver/wiki/Bulk-Write-Operations

Bulk write operations are not yet available in Mongoid but are planned for a future release based on a new version of the "mongo" Ruby driver.

Gary Murakami
  • 3,392
  • 1
  • 16
  • 20