programing

Mongoid를 사용한 배치 삽입/업데이트?

iphone6s 2023. 5. 2. 22:27
반응형

Mongoid를 사용한 배치 삽입/업데이트?

저는 다른 모든 사람들과 구글을 검색했지만 답을 찾지 못했습니다.질문은 다음과 같습니다.

안녕하세요, MongoDB에 Mongoid로 배치 삽입은 어떻게 하나요?

루비 몽고 드라이버 삽입 방법을 사용하여 해시 배치 배열을 삽입할 수 있습니다.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.

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

몽고이드의Model.create메소드는 배열을 허용하여 문서를 만들 수 있습니다.

Mongoid 문서에서:

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

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

언급URL : https://stackoverflow.com/questions/3772378/batch-insert-update-using-mongoid

반응형