41

私はグーグルで検索しましたが、答えが見つかりませんでした。質問は:

こんにちは、Mongoid を使用して MongoDB に一括挿入するにはどうすればよいですか?

4

4 に答える 4

55

ruby mongo ドライバーの insert メソッドを使用して、ハッシュのバッチ配列を挿入できます。任意の Mongoid クラスから、コレクションを呼び出してアクセスできます。

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 に答える