使用Mongoid批量插入/更新?

Aut*_*act 40 mongodb mongoid

我用谷歌搜索了所有其他人,但我找不到答案.问题是:

嗨,我怎么能用Mongoid批量插入到MongoDB?

tom*_*eng 55

您可以使用ruby mongo驱动程序的insert方法插入一批哈希值.从任何Mongoid类,您可以调用集合来访问它.

batch = [{:name => "mongodb"}, {:name => "mongoid"}]  
Article.collection.insert(batch)
Run Code Online (Sandbox Code Playgroud)

  • 要记住的一个非常重要的一点是,通过这样做,你绕过了mongoid.yml选项.因此,如果您使用它,请确保在需要时通知他们,例如:Article.with(safe:true).collection.insert(batch) (5认同)
  • @HarisKrajina - 在mongoid的更新版本中,您需要使用'insert_many'方法.希望这可以帮助, (2认同)

Dam*_*lic 26

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

@page_views << page_view.as_document
Run Code Online (Sandbox Code Playgroud)

...

PageView.collection.insert(@page_views)
Run Code Online (Sandbox Code Playgroud)

  • 跳过验证 (8认同)
  • @Jay`mongoid`或`mongodb`解决了一个对象已经存在并执行更新的事实吗?还是有必要过滤掉那些? (2认同)

小智 5

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

来自 Mongoid 文档:

Person.create([
  { first_name: "Heinrich", last_name: "Heine" },
  { first_name: "Willy", last_name: "Brandt" }
])
Run Code Online (Sandbox Code Playgroud)

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

  • 这仍然一一创建它们:( (3认同)

liu*_*kgg 5

您可以使用此:

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

而且我发现“插入”对我不起作用(Monogoid 5.1.3):

NoMethodError: undefined method `insert' for # <Mongo::Collection:0x007fbdbc9b1cd0>
Did you mean?  insert_one
               insert_many
               inspect
Run Code Online (Sandbox Code Playgroud)

这是来自“ 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
Run Code Online (Sandbox Code Playgroud)