How to bulk update/upsert with mongoid/mongodb?
mongodb, mongoid, ruby, ruby-on-rails
Solution
The best answer in the referenced question can be simplified to
id_status = [['5471944843687229cdfb0000','closed'], ...]
bulk_order = id_status.map do |id, status| # Using array destructuration
{ update_one:
{
filter: { _id: id },
update: { :'$set' => {
status: status,
}}
}
}
end
YourCollection.collection.bulk_write(bulk_order)
Problem
I have a database with millions of `Order`documents. I batch insert them with the following method: ``` Order.collection.insert([ {:_id=>BSON::ObjectId('5471944843687229cdfb0000'), :status=>"open", :name=> "Benny"}, {:_id=>BSON::ObjectId('5471944843687229cdfc0000'), :status=>"open", :name=> "Allan"} ]) ``` I regularly need to update the `status` attribute on the orders. It would be way to inefficient to update them individually with the `update_attribute` method. How do I bulk update multiple MongoDB documents? The desired solution can best be described with the below "fictional" code: ``` # IMPORTANT: The exemplified upsert method does not exist Order.collection.upsert([ {:_id=>BSON::ObjectId('5471944843687229cdfb0000'), :status=>"closed"}, {:_id=>BSON::ObjectId('5471944843687229cdfc0000'), :status=>"some_other_status"} ]) ``` Fyi, there might be a similar question/answer in this SO post, but in all honesty I don't follow the answer.