Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bulk update/upsert with mongoid/mongodb?

I have a database with millions of Orderdocuments. 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.

like image 633
Cjoerg Avatar asked Oct 20 '25 02:10

Cjoerg


1 Answers

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)
like image 53
Cyril Duchon-Doris Avatar answered Oct 21 '25 17:10

Cyril Duchon-Doris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!