私はグーグルで検索しましたが、答えが見つかりませんでした。質問は:
こんにちは、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