mongoid批量操作 - initialize_unordered_bulk_op

时间:2016-03-20 10:10:22

标签: ruby mongodb mongoid

如何使用mongoid实现无序批量操作? mongo_unordered_bulk_write

bulk = coll.initialize_unordered_bulk_op
bulk.insert({'_id' => 1})
bulk.insert({'_id' => 1}) # duplicate key
bulk.insert({'_id' => 3})
bulk.insert({'_id' => 3}) # duplicate key
bulk.execute

1 个答案:

答案 0 :(得分:2)

Mongoid类有一个.collection访问器,可以从核心驱动程序访问Collection对象:

bulk = Class.collection.initialize_unordered_bulk_op

等等。

但现代驱动程序通常首选使用更一致的bulk_write()方法和标准对象数组:

 ops = [];

 ops.push({ "insert_one" => { "_id" => 1 } })
 ops.push({ "insert_one" => { "_id" => 1 } })
 ops.push({ "insert_one" => { "_id" => 3 } })
 ops.push({ "insert_one" => { "_id" => 3 } })

 Class.collection.bulk_write(ops,{ "ordered" => false })

如果您只是进行插入而不是混合写入操作类型,则甚至是insert_many()

 Class.collection.insert_many([
     { "_id" => 1 },
     { "_id" => 1 },
     { "_id" => 3 },
     { "_id" => 3 }
 ],{ "ordered" => false })