Write Operations
On this page
- Overview
- Sample Model
- Insert Documents
- Insert a Document Examples
- Insert Multiple Documents Example
- Modify Documents
- Update a Document Examples
- Update Multiple Documents Example
- Update or Insert in a Single Operation
- Upsert Method
- Update Method
- Update Arrays in a Document
- Add Values to an Array Example
- Remove Values From an Array Example
- Update the Value of an Array Element Example
- Delete Documents
- Delete a Document Examples
- Delete Multiple Documents Examples
Overview
In this guide, you can learn how to use Laravel MongoDB to perform write operations on your MongoDB collections. Write operations include inserting, updating, and deleting data based on specified criteria.
This guide shows you how to perform the following tasks:
Sample Model
The write operations in this guide reference the following Eloquent model class:
namespace App\Models; use MongoDB\Laravel\Eloquent\Model; class Concert extends Model { protected $connection = 'mongodb'; protected $fillable = ['performer', 'venue', 'genres', 'ticketsSold', 'performanceDate']; protected $casts = ['performanceDate' => 'datetime']; }
Tip
The $fillable
attribute lets you use Laravel mass assignment for insert
operations. To learn more about mass assignment, see Customize Mass Assignment
in the Eloquent Model Class documentation.
The $casts
attribute instructs Laravel to convert attributes to common
data types. To learn more, see Attribute Casting
in the Laravel documentation.
Insert Documents
In this section, you can learn how to insert documents into MongoDB collections from your Laravel application by using Laravel MongoDB.
When you insert the documents, ensure the data does not violate any
unique indexes on the collection. When inserting the first document of a
collection or creating a new collection, MongoDB automatically creates a
unique index on the _id
field.
For more information on creating indexes on MongoDB collections by using the Laravel schema builder, see the Manage Indexes section of the Schema Builder documentation.
To learn more about Eloquent models in the Laravel Integration, see the Eloquent Models section.
Insert a Document Examples
These examples show how to use the save()
Eloquent method to insert an
instance of a Concert
model as a MongoDB document.
When the save()
method succeeds, you can access the model instance on
which you called the method.
If the operation fails, the model instance is assigned null
.
This example code performs the following actions:
Creates a new instance of the
Concert
modelAssigns string values to the
performer
andvenue
fieldsAssigns an array of strings to the
genre
fieldAssigns a number to the
ticketsSold
fieldAssigns a date to the
performanceDate
field by using theCarbon
packageInserts the document by calling the
save()
method
$concert = new Concert(); $concert->performer = 'Mitsuko Uchida'; $concert->venue = 'Carnegie Hall'; $concert->genres = ['classical']; $concert->ticketsSold = 2121; $concert->performanceDate = Carbon::create(2024, 4, 1, 20, 0, 0, 'EST'); $concert->save();
You can retrieve the inserted document's _id
value by accessing the model's
id
member, as shown in the following code example:
$insertedId = $concert->id;
If you enable mass assignment by defining either the $fillable
or
$guarded
attributes, you can use the Eloquent model create()
method
to perform the insert in a single call, as shown in the following example:
$insertResult = Concert::create([ 'performer' => 'The Rolling Stones', 'venue' => 'Soldier Field', 'genres' => [ 'rock', 'pop', 'blues' ], 'ticketsSold' => 59527, 'performanceDate' => Carbon::create(2024, 6, 30, 20, 0, 0, 'CDT'), ]);
To learn more about the Carbon PHP API extension, see the Carbon GitHub repository.
Insert Multiple Documents Example
This example shows how to use the insert()
Eloquent method to insert
multiple instances of a Concert
model as MongoDB documents. This bulk
insert method reduces the number of calls your application needs to make
to save the documents.
When the insert()
method succeeds, it returns the value 1
.
If it fails, it throws an exception.
The example code saves multiple models in a single call by passing them as
an array to the insert()
method:
Note
This example wraps the dates in the MongoDB\BSON\UTCDateTime class to convert it to a type MongoDB can serialize because Laravel skips attribute casting on bulk insert operations.
$data = [ [ 'performer' => 'Brad Mehldau', 'venue' => 'Philharmonie de Paris', 'genres' => [ 'jazz', 'post-bop' ], 'ticketsSold' => 5745, 'performanceDate' => new UTCDateTime(Carbon::create(2025, 2, 12, 20, 0, 0, 'CET')), ], [ 'performer' => 'Billy Joel', 'venue' => 'Madison Square Garden', 'genres' => [ 'rock', 'soft rock', 'pop rock' ], 'ticketsSold' => 12852, 'performanceDate' => new UTCDateTime(Carbon::create(2025, 2, 12, 20, 0, 0, 'CET')), ], ]; Concert::insert($data);
Modify Documents
In this section, you can learn how to modify documents in your MongoDB collection from your Laravel application. Use update operations to modify existing documents or to insert a document if none match the search criteria.
You can persist changes on an instance of an Eloquent model or use Eloquent's fluent syntax to chain an update operation on methods that return a Laravel collection object.
This section provides examples of the following update operations:
Update a Document Examples
You can update a document in the following ways:
Modify an instance of the model and save the changes by calling the
save()
method.Chain methods to retrieve an instance of a model and perform updates on it by calling the
update()
method.
The following example shows how to update a document by modifying an instance
of the model and calling its save()
method:
$concert = Concert::first(); $concert->venue = 'Manchester Arena'; $concert->ticketsSold = 9543; $concert->save();
When the save()
method succeeds, the model instance on which you called the
method contains the updated values.
If the operation fails, the Laravel Integration assigns the model instance a null
value.
The following example shows how to update a document by chaining methods to retrieve and update the first matching document:
$concert = Concert::where(['performer' => 'Brad Mehldau']) ->orderBy('_id') ->first() ->update(['venue' => 'Manchester Arena', 'ticketsSold' => 9543]);
Note
The orderBy()
call sorts the results by the _id
field to
guarantee a consistent sort order. To learn more about sorting in MongoDB,
see the Natural order
glossary entry in the Server manual.
When the update()
method succeeds, the operation returns the number of
documents updated.
If the retrieve part of the call does not match any documents, the Laravel Integration returns the following error:
Error: Call to a member function update() on null
Update Multiple Documents Example
To perform an update on one or more documents, chain the update()
method to the results of a method that retrieves the documents as a
Laravel collection object, such as where()
.
The following example shows how to chain calls to retrieve matching documents and update them:
Concert::whereIn('venue', ['Philharmonie de Paris', 'Soldier Field']) ->update(['venue' => 'Concertgebouw', 'ticketsSold' => 0]);
When the update()
method succeeds, the operation returns the number of
documents updated.
If the retrieve part of the call does not match any documents in the collection, the Laravel Integration returns the following error:
Error: Call to a member function update() on null
Update or Insert in a Single Operation
An upsert operation lets you perform an update or insert in a single operation. This operation streamlines the task of updating a document or inserting one if it does not exist.
Starting in v4.7, you can perform an upsert operation by using either of the following methods:
upsert()
: When you use this method, you can perform a batch upsert to change or insert multiple documents in one operation.update()
: When you use this method, you must specify theupsert
option to update all documents that match the query filter or insert one document if no documents are matched. Only this upsert method is supported in versions v4.6 and earlier.
Upsert Method
The upsert(array $values, array|string $uniqueBy, array|null
$update)
method accepts the following parameters:
$values
: Array of fields and values that specify documents to update or insert.$uniqueBy
: List of fields that uniquely identify documents in your first array parameter.$update
: Optional list of fields to update if a matching document exists. If you omit this parameter, the Laravel Integration updates all fields.
To specify an upsert in the upsert()
method, set parameters
as shown in the following code example:
YourModel::upsert( [/* documents to update or insert */], '/* unique field */', [/* fields to update */], );
Example
This example shows how to use the upsert()
method to perform an update or insert in a single operation. Click the
VIEW OUTPUT button to see the resulting data changes when
there is a document in which the value of performer
is 'Angel
Olsen'
in the collection already:
Concert::upsert([ ['performer' => 'Angel Olsen', 'venue' => 'Academy of Music', 'ticketsSold' => 275], ['performer' => 'Darondo', 'venue' => 'Cafe du Nord', 'ticketsSold' => 300], ], 'performer', ['ticketsSold']);
{ "_id": "...", "performer": "Angel Olsen", "venue": "State Theatre", "genres": [ "indie", "rock" ], "ticketsSold": 275, "updated_at": ... }, { "_id": "...", "performer": "Darondo", "venue": "Cafe du Nord", "ticketsSold": 300, "updated_at": ... }
In the document in which the value of performer
is 'Angel
Olsen'
, the venue
field value is not updated, as the upsert
specifies that the update applies only to the ticketsSold
field.
Update Method
To specify an upsert in an update()
method, set the upsert
option to
true
as shown in the following code example:
YourModel::where(/* match criteria */) ->update( [/* update data */], ['upsert' => true]);
When the update()
method is chained to a query, it performs one of the
following actions:
If the query matches documents, the
update()
method modifies the matching documents.If the query matches zero documents, the
update()
method inserts a document that contains the update data and the equality match criteria data.
Example
This example shows how to pass the upsert
option to the update()
method to perform an update or insert in a single operation. Click the
VIEW OUTPUT button to see the example document inserted when no
matching documents exist:
Concert::where(['performer' => 'Jon Batiste', 'venue' => 'Radio City Music Hall']) ->update( ['genres' => ['R&B', 'soul'], 'ticketsSold' => 4000], ['upsert' => true], );
{ "_id": "660c...", "performer": "Jon Batiste", "venue": "Radio City Music Hall", "genres": [ "R&B", "soul" ], "ticketsSold": 4000, "updated_at": ... }
Update Arrays in a Document
In this section, you can see examples of the following operations that update array values in a MongoDB document:
These examples modify the sample document created by the following insert operation:
Concert::create([ 'performer' => 'Mitsuko Uchida', 'genres' => ['classical', 'dance-pop'], ]);
Add Values to an Array Example
This section shows how to use the push()
method to add values to an array
in a MongoDB document. You can pass one or more values to add and set the
optional parameter unique
to true
to skip adding any duplicate values
in the array. The following code example shows the structure of a push()
method call:
YourModel::where(<match criteria>) ->push( <field name>, [<values>], // array or single value to add unique: true); // whether to skip existing values
The following example shows how to add the value "baroque"
to
the genres
array field of a matching document. Click the
VIEW OUTPUT button to see the updated document:
Concert::where('performer', 'Mitsuko Uchida') ->push( 'genres', ['baroque'], );
{ "_id": "660eb...", "performer": "Mitsuko Uchida", "genres": [ "classical", "dance-pop", ], "updated_at": ..., "created_at": ... }
Remove Values From an Array Example
This section shows how to use the pull()
method to remove values from
an array in a MongoDB document. You can pass one or more values to remove
from the array. The following code example shows the structure of a
pull()
method call:
YourModel::where(<match criteria>) ->pull( <field name>, [<values>]); // array or single value to remove
The following example shows how to remove array values "classical"
and
"dance-pop"
from the genres
array field. Click the
VIEW OUTPUT button to see the updated document:
Concert::where('performer', 'Mitsuko Uchida') ->pull( 'genres', ['dance-pop', 'classical'], );
{ "_id": "660e...", "performer": "Mitsuko Uchida", "genres": [], "updated_at": ..., "created_at": ... }
Update the Value of an Array Element Example
This section shows how to use the $
positional operator to update specific
array elements in a MongoDB document. The $
operator represents the first
array element that matches the query. The following code example shows the
structure of a positional operator update call on a single matching document:
Note
Currently, the Laravel Integration offers this operation only on the DB
facade
and not on the Eloquent ORM.
DB::connection('mongodb') ->getCollection(<collection name>) ->updateOne( <match criteria>, ['$set' => ['<array field>.$' => <replacement value>]]);
The following example shows how to replace the array value "dance-pop"
with "contemporary"
in the genres
array field. Click the
VIEW OUTPUT button to see the updated document:
$match = ['performer' => 'Mitsuko Uchida', 'genres' => 'dance-pop']; $update = ['$set' => ['genres.$' => 'contemporary']]; DB::connection('mongodb') ->getCollection('concerts') ->updateOne($match, $update);
{ "_id": "660e...", "performer": "Mitsuko Uchida", "genres": [ "classical", "contemporary" ], "updated_at": ..., "created_at": ... }
To learn more about array update operators, see Array Update Operators in the Server manual.
Delete Documents
In this section, you can learn how to delete documents from a MongoDB collection by using the Laravel Integration. Use delete operations to remove data from your MongoDB database.
This section provides examples of the following delete operations:
To learn about the Laravel features available in the Laravel Integration that modify delete behavior, see the following sections:
Soft delete, which lets you mark documents as deleted instead of removing them from the database
Pruning, which lets you define conditions that qualify a document for automatic deletion
Delete a Document Examples
You can delete one document in the following ways:
Call the
$model->delete()
method on an instance of the model.Call the
Model::destroy($id)
method on the model, passing it the id of the document to be deleted.Chain methods to retrieve and delete an instance of a model by calling the
delete()
method.
The following example shows how to delete a document by calling $model->delete()
on an instance of the model:
$concert = Concert::first(); $concert->delete();
When the delete()
method succeeds, the operation returns the number of
documents deleted.
If the retrieve part of the call does not match any documents in the collection,
the operation returns 0
.
The following example shows how to delete a document by passing the value of
its id to the Model::destroy($id)
method:
$id = 'MSG-0212252000'; Concert::destroy($id);
When the destroy()
method succeeds, it returns the number of documents
deleted.
If the id value does not match any documents, the destroy()
method
returns returns 0
.
The following example shows how to chain calls to retrieve the first matching document and delete it:
Concert::where('venue', 'Carnegie Hall') ->limit(1) ->delete();
Note
The orderBy()
call sorts the results by the _id
field to
guarantee a consistent sort order. To learn more about sorting in MongoDB,
see the Natural order
glossary entry in the Server manual.
When the delete()
method succeeds, it returns the number of documents
deleted.
If the where()
method does not match any documents, the delete()
method
returns returns 0
.
Delete Multiple Documents Examples
You can delete multiple documents in the following ways:
Call the
Model::destroy($ids)
method, passing a list of the ids of the documents or model instances to be deleted.Chain methods to retrieve a Laravel collection object that references multiple objects and delete them by calling the
delete()
method.
The following example shows how to delete a document by passing an array of
id values, represented by $ids
, to the destroy()
method:
$ids = [3, 5, 7, 9]; Concert::destroy($ids);
Tip
The destroy()
method performance suffers when passed large lists. For
better performance, use Model::whereIn('id', $ids)->delete()
instead.
When the destroy()
method succeeds, it returns the number of documents
deleted.
If the id values do not match any documents, the destroy()
method
returns returns 0
.
The following example shows how to chain calls to retrieve matching documents and delete them:
Concert::where('ticketsSold', '>', 7500) ->delete();
When the delete()
method succeeds, it returns the number of documents
deleted.
If the where()
method does not match any documents, the delete()
method
returns 0
.