Lote insertar / actualizar usando Mongoid?


Busqué en Google y todos los demás, pero no encontré la respuesta. La pregunta es:

Hola, ¿cómo puedo hacer la inserción por lotes con Mongoid a MongoDB?

Author: Autodidact, 2010-09-22

4 answers

Puede insertar una matriz por lotes de hashes utilizando el método de inserción del controlador ruby mongo. Desde cualquier clase Mongoid, puede llamar a collection para acceder a ella.

batch = [{:name => "mongodb"}, {:name => "mongoid"}]  
Article.collection.insert(batch)
 53
Author: tommy chheng,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-21 22:35:57

Si desea insertar por lotes documentos Mongoid (modelos) en lugar de hashes, llame al método as_document de su modelo antes de colocarlo en el array:

@page_views << page_view.as_document

...

PageView.collection.insert(@page_views)
 25
Author: Damir Bulic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-12 12:45:47

Puedes usar esto:

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

Y encuentro que "insertar" no funciona para mí (Monogoid 5.1.3):

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

Este es el código fuente de "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
Author: liukgg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-08 08:09:15

El método Model.create de Mongoid puede aceptar una matriz para crear documentos.

De los documentos Mongoid:

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

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

 2
Author: dcrane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-04 18:14:28