Wsadowe wstawianie / aktualizowanie za pomocą Mongoid?

Wygooglowałem i wszystkie inne, ale nie znalazłem odpowiedzi. Pytanie brzmi:

Witam, jak mogę wstawić wsad z Mongoid do MongoDB?

Author: Autodidact, 2010-09-22

4 answers

Możesz wstawić batch array z hashami używając metody Wstaw sterownika ruby mongo. Z dowolnej klasy Mongoid możesz wywołać kolekcję, aby uzyskać do niej dostęp.

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/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-21 22:35:57

Jeśli chcesz wsadowo wstawiać dokumenty Mongoid (modele) zamiast hashów, wywołaj metodę as_document swojego modelu przed umieszczeniem go w tablicy:

@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/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-12 12:45:47

Możesz użyć tego:

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

A ja uważam, że "insert" nie działa dla mnie (Monogoid 5.1.3):

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

To jest kod źródłowy z "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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-08 08:09:15

Metoda Mongoid Model.create może przyjmować tablicę do tworzenia dokumentów.

Z Mongoid docs:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-04 18:14:28