代码之家  ›  专栏  ›  技术社区  ›  millisami

使用mongoid批量插入/更新?

  •  40
  • millisami  · 技术社区  · 14 年前

    我和其他人都在谷歌上搜索,但没找到答案。问题是:

    您好,如何将MongoID批量插入MongoDB?

    4 回复  |  直到 8 年前
        1
  •  54
  •   tommy chheng    14 年前

    batch = [{:name => "mongodb"}, {:name => "mongoid"}]  
    Article.collection.insert(batch)
    
        2
  •  26
  •   Damir Bulic    13 年前

    @page_views << page_view.as_document
    

    PageView.collection.insert(@page_views)
    
        3
  •  4
  •   liukgg    8 年前

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

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

    # 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
  •  2
  •   Litty    8 年前

    Model.create

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

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