我有一个包含数百万个Order
文档的数据库。我使用以下方法批量插入它们:
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 ,但老实说,我不遵循答案。
最佳答案
引用问题中的最佳答案可以简化为
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)
关于ruby-on-rails - 如何使用 mongoid/mongodb 批量更新/更新插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27093619/