41

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

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

4

4 回答 4

55

您可以使用 ruby​​ mongo 驱动程序的 insert 方法插入一批哈希数组。在任何 Mongoid 类中,您都可以调用 collection 来访问它。

batch = [{:name => "mongodb"}, {:name => "mongoid"}]  
Article.collection.insert(batch)
于 2010-10-21T22:35:57.313 回答
26

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

@page_views << page_view.as_document

...

PageView.collection.insert(@page_views)
于 2011-09-12T12:45:47.630 回答
8

你可以使用这个:

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
于 2016-07-08T07:41:35.427 回答
4

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

来自 Mongoid 文档:

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

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

于 2016-02-04T17:26:56.103 回答