如何使用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
答案 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 })