批量插入/更新使用Mongoid?

我GOOGLE和所有其他人,但我没有find答案。 问题是:

嗨,我怎样才能批量插入与Mongoid到MongoDB?

您可以使用ruby mongo驱动程序的insert方法插入批处理散列数组。 从任何Mongoid类,你可以调用集合来访问它。

batch = [{:name => "mongodb"}, {:name => "mongoid"}] Article.collection.insert(batch) 

如果要批量插入Mongoid文档(模型)而不是散列,请在放入数组之前调用模型的as_document方法:

 @page_views << page_view.as_document 

 PageView.collection.insert(@page_views) 

你可以使用这个:

 books = [{:name => "Harry Potter"}, {:name => "Night"}] Book.collection.insert_many(books) 

而我发现“插入”不适合我(Monogoid 5.1.3):

 NoMethodError: undefined method `insert' for # <Mongo::Collection:0x007fbdbc9b1cd0> Did you mean? insert_one insert_many inspect 

这是“lib / mongo / collection.rb”的源代码:

 # Insert the provided documents into the collection. # # @example Insert documents into the collection. # collection.insert_many([{ name: 'test' }]) # # @param [ Array<Hash> ] documents The documents to insert. # @param [ Hash ] options The insert options. # # @return [ Result ] The database response wrapper. # # @since 2.0.0 def insert_many(documents, options = {}) inserts = documents.map{ |doc| { :insert_one => doc }} bulk_write(inserts, options) end 

Mongoid的Model.create方法可以接受一个数组来创build文档。

从Mongoid docs:

 Person.create([ { first_name: "Heinrich", last_name: "Heine" }, { first_name: "Willy", last_name: "Brandt" } ]) 

https://docs.mongodb.org/ecosystem/tutorial/mongoid-persistence/