Navigation

Bulk Operations

The bulk write API sends several write operations to the server in a single command. Use the bulk write API to reduce the number of network round-trips when performing several writes at a time.

If the ordered option is set to true (which is the default), the operations are applied in order and if any operation fails, subsequent operations are not attempted. If the ordered option is set to false, all specified operations are attempted.

The bulk_write method takes three arguments:

  • A list of operations to execute.
  • The ordered option taking a boolean value. Defaults to true.
  • The write concern option. Defaults to the collection’s write concern.

Valid bulk write operations are the following:

insert_one

{ :insert_one => { :x => 1 } }

Note

There is no insert_many operation. To insert multiple documents, specify multiple insert_one operations.

update_one

{ :update_one => { :filter => { :x => 1 },
                   :update => { '$set' =>  { :x => 2 } },
                   :upsert => true } # upsert is optional and defaults to false
 }

update_many

{ :update_many => { :filter => { :x => 1 },
                    :update => { '$set' =>  { :x => 2 } },
                    :upsert => true } # upsert is optional and defaults to false
 }

The following example shows how to pass operations to the bulk_write method.

coll = client['documents']
coll.bulk_write([ { :insert_one => { :x => 1 }
                  },
                  { :update_one => { :filter => { :x => 1 },
                                     :update => {'$set' => { :x => 2 } }
                                   }
                  },
                  { :replace_one => { :filter => { :x => 2 },
                                      :replacement => { :x => 3 }
                                    }
                  }
                ],
                :ordered => true)

replace_one

{ :replace_one => { :filter => { :x => 1 },
                    :replacement => { :x => 2 },
                    :upsert => true } # upsert is optional and defaults to false
 }

delete_one

{ :delete_one => { :filter => { :x => 1 } } }

delete_many

{ :delete_many => { :filter => { :x => 1 } } }
←   Aggregation Text Search  →