Batch insert/update using Mongoid?

六眼飞鱼酱① 提交于 2019-12-17 07:07:18

问题


I googled and all others, but I didn't find the answer. The question is:

Hi, how can I do batch insert with Mongoid to MongoDB?


回答1:


You can insert a batch array of hashes using the ruby mongo driver's insert method. From any Mongoid class, you can call collection to access it.

batch = [{:name => "mongodb"}, {:name => "mongoid"}]  
Article.collection.insert(batch)



回答2:


If you want to batch insert Mongoid documents (models) instead of hashes, call your model's as_document method before placing it into array:

@page_views << page_view.as_document

...

PageView.collection.insert(@page_views)



回答3:


You can use this:

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

And I find that "insert" does not work for me(Monogoid 5.1.3):

NoMethodError: undefined method `insert' for # <Mongo::Collection:0x007fbdbc9b1cd0>
Did you mean?  insert_one
               insert_many
               inspect

This is the source code from "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



回答4:


Mongoid's Model.create method can accept an array to create documents.

From the Mongoid docs:

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

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



来源:https://stackoverflow.com/questions/3772378/batch-insert-update-using-mongoid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!