You can update a document in a collection by retrieving a single
document and calling the update() method on an Eloquent model.
Pass a query filter to the where() method, sort the matching
documents, and call the first() method to retrieve only the first
document. Then, update this matching document 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.
Example
This example performs the following actions:
Uses the
MovieEloquent model to represent themoviescollection in thesample_mflixdatabaseUpdates a document from the
moviescollection that matches the query filterPrints the number of updated documents
The example calls the following methods on the Movie model:
where(): Matches documents in which the value of thetitlefield is"Carol"orderBy(): Sorts matched documents by their ascending_idvaluesfirst(): Retrieves only the first matching documentupdate(): Updates the value of theimdb.ratingnested field to from6.9to7.3and the value of theimdb.votesnested field from493to142000
$updates = Movie::where('title', 'Carol') ->orderBy('id') ->first() ->update([ 'imdb' => [ 'rating' => 7.3, 'votes' => 142000, ], ]); echo 'Updated documents: ' . $updates;
Updated documents: 1
To learn how to edit your Laravel application to run the usage example, see the Usage Examples landing page.