我有一个数以百万计的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