我有一个包含数百万个订单
文档的数据库。我使用以下方法批量插入它们:
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"}
])
提醒一下,这个SO帖子可能有一个类似的问题/答案,但说实话我并不理解那个答案。