嗨,我如何使用Mongoid批量插入到MongoDB?
答案 0 :(得分:54)
您可以使用ruby mongo驱动程序的insert方法插入一批哈希值。从任何Mongoid类中,您都可以调用collection来访问它。
batch = [{:name => "mongodb"}, {:name => "mongoid"}]
Article.collection.insert(batch)
答案 1 :(得分:26)
如果要批量插入Mongoid文档(模型)而不是散列,请在将模型放入数组之前调用模型的as_document方法:
@page_views << page_view.as_document
...
PageView.collection.insert(@page_views)
答案 2 :(得分:4)
您可以使用:
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
答案 3 :(得分:2)
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/