我有一個數以百萬計的Order
文件的數據庫。我批量使用以下方法插入它們:如何批量更新/插入mongoid/mongodb?
Order.collection.insert([
{:_id=>BSON::ObjectId('5471944843687229cdfb0000'), :status=>"open", :name=> "Benny"},
{:_id=>BSON::ObjectId('5471944843687229cdfc0000'), :status=>"open", :name=> "Allan"}
])
我經常需要更新訂單上的status
屬性。如果使用update_attribute
方法分別更新它們,效率會很低。
如何批量更新多個MongoDB文檔?
所需的解決方案最能與下面的「虛構的」代碼描述:
# 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"}
])
據透露,有可能是一個類似的問題/回答in this SO post,但在所有誠實,我不跟着答案。
在鏈接的問題的答案給出了一個很長的例子,但你明白(和向後從工作)的重點線是這樣的:「{update:Product.collection_name.to_s,updates:updates,ordered:false}」這是更新命令,需要多個更新指令。 「更新」參數是要更新的列表 - 通過代碼向後看,以查看如何構建這批更新。 – 2014-12-26 23:26:51
嗨@AsyaKamsky,你可以把它作爲一個簡短的回答這個問題嗎?我只有2天的時間才能獎賞答案。 – ChristofferJoergensen 2014-12-27 03:58:14
[Mongoid Batch Update/Upsert Alternative?]可能重複(http://stackoverflow.com/questions/25550690/mongoid-batch-update-upsert-alternative) – akostadinov 2017-02-16 20:20:00