Docs Menu

Update Multiple Documents

On this page

You can update multiple documents in a collection by calling the update() method on a query builder.

Pass a query filter to the where() method to retrieve documents that meet a set of criteria. Then, update the matching documents by passing your intended document changes to the update() method.

Tip

To learn more about updating data with the Laravel Integration, see the Modify Documents section of the Write Operations guide.

Select from the following Eloquent and Query Builder tabs to view usage examples for the same operation that use each corresponding query syntax:

This example performs the following actions:

  • Uses the Movie Eloquent model to represent the movies collection in the sample_mflix database

  • Updates documents from the movies collection that match a query filter

  • Prints the number of updated documents

The example calls the following methods on the Movie model:

  • where(): Matches documents in which the value of the imdb.rating nested field is greater than 9.0

  • update(): Updates the matching documents by adding an acclaimed field and setting its value to true, then returns the number of updated documents

$updates = Movie::where('imdb.rating', '>', 9.0)
->update(['acclaimed' => true]);
echo 'Updated documents: ' . $updates;
Updated documents: 20

This example performs the following actions:

  • Accesses the movies collection by calling the table() method from the DB facade

  • Updates documents from the movies collection that match a query filter

  • Prints the number of updated documents

The example calls the following query builder methods:

  • where(): Matches documents in which the value of the imdb.rating nested field is greater than 9.0

  • update(): Updates the matching documents by adding an acclaimed field and setting its value to true, then returns the number of updated documents

$updates = DB::table('movies')
->where('imdb.rating', '>', 9.0)
->update(['acclaimed' => true]);
echo 'Updated documents: ' . $updates;
Updated documents: 20

To learn how to edit your Laravel application to run the usage example, see the Usage Examples landing page.

On this page