Operations with Builders
On this page
Overview
In this guide, you can learn about the builder classes that the PHP library provides to create types used in your operations. You can use the builder classes and factory methods from the Aggregation Builder feature to create filters for other operations such as find, update, and delete operations. To learn more about the Aggregation Builder, see the Aggregation Builder section of the Aggregation guide.
Using builders to create queries helps you identify errors at compile time and avoid them at runtime. This guide provides information on builder classes that you can use to perform the following tasks:
Note
Setting Operation Options
You cannot specify options by using factory methods for the equivalent
aggregation stages. For example, you cannot use the Stage::limit()
method
to set a returned documents limit on your find operation. You must specify
options by using the string-based syntax, as shown in the following code:
$options = [ 'limit' => 5, '<option name>' => '<specification>', ];
This guide provides examples of how to use builders in non-aggregation operations. To view aggregation examples, see the Transform Your Data with Aggregation guide.
Sample Data
The examples in this guide use the shipwrecks
collection in the
sample_geospatial
database from the Atlas sample datasets. To access this collection from your PHP application,
instantiate a MongoDB\Client
that connects to an Atlas cluster
and assign the following value to your $collection
variable:
$collection = $client->sample_geospatial->shipwrecks;
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.
Import Builder Classes
To run the examples in this guide, you must import the following classes into your application:
use MongoDB\Builder\Pipeline; use MongoDB\Builder\Query; use MongoDB\Builder\Stage;
Create a Filter
You can use factory methods from the Query
builder class to create
filter definitions to use in find, update, and delete operations. When
using the Query::query()
factory method to create queries, you can
use named argument syntax and implement type safety. To learn more about
creating filters, see the Specify a Query guide.
The following steps describe how to create a filter definition by using builders:
Call the
Query::query()
method to create a query.Pass the field name to filter on and a factory method from the
Query
class. You can pass one or more pairs of field names and criteria in the filter to apply multiple clauses.
The following code shows the template to create a filter definition by using builders:
$filter = Query::query( <field name>: Query::<factory method>(<parameters>), <field name>: Query::<factory method>(<parameters>), ... );
To combine query criteria by using logical query operators
($and
, $or
, $not
, $nor
), you can use the following
query template:
$filter = Query::<logical operator>( Query::query(<field name>: Query::<factory method>(<parameters>)), Query::query(<field name>: Query::<factory method>(<parameters>)), ... );
To learn more, see Logical Query Operators in the MongoDB Server manual.
The following sections provide examples that use builders to create filter definitions for different operations.
Retrieve Example
This example performs the following actions:
Uses the
Query::eq()
factory method to match documents in which thefeature_type
field value is'Wrecks - Visible'
Uses the
Query::near()
factory method to match documents in which thecoordinates
location field is within10000
meters of the specified coordinatesCalls the
MongoDB\Collection::find()
method to retrieve the matching documentsPrints the matching documents
// Creates a query filter by using builders and // retrieves matching documents $docs = $collection->find( Query::query( feature_type: Query::eq('Wrecks - Visible'), coordinates: Query::near( Query::geometry( type: 'Point', coordinates: [-79.9, 9.3], ), maxDistance: 10000, ) ) ); // Prints matching documents foreach ($docs as $doc) { echo json_encode($doc), PHP_EOL; }
{"_id":...,"feature_type":"Wrecks - Visible","coordinates":[-79.9137115,9.3390503],...} {"_id":...,"feature_type":"Wrecks - Visible","coordinates":[-79.9357223,9.3340302],...} {"_id":...,"feature_type":"Wrecks - Visible","coordinates":[-79.9081268,9.3547792],...} // Results truncated
To learn more about find operations, see the Retrieve Data guide.
Delete Example
This example performs the following actions:
Uses the
Query::or()
factory method to match documents that satisfy the either of the following query clauses:Clause that uses the
Query::regex()
factory method to check if thefeature_type
field value contains the string'nondangerous'
Clause that uses the
Query::gt()
factory method to check if thedepth
field value is greater than10.0
Calls the
MongoDB\Collection::deleteOne()
method to delete the first matching documentPrints the number of deleted documents
// Creates a query filter by using builders // and deletes the first matching document $result = $collection->deleteOne( Query::or( Query::query(feature_type: Query::regex('nondangerous$', '')), Query::query(depth: Query::gt(10.0)), ) ); // Prints number of deleted documents echo 'Deleted documents: ', $result->getDeletedCount(), PHP_EOL;
Deleted documents: 1
To learn more about delete operations, see the Delete Documents guide.
Define an Update Document
You can use factory methods from the Stage
builder class to create
update documents. Update documents describe the updates to make to target
documents. To learn more about updating documents, see the
Update Documents guide.
The following steps describe how to create an update document by using builders:
Create a
Pipeline
instance.Pass one or more stages by calling methods from the
Stage
class such asStage::set()
and passing field names and values.
The following code shows the template to define an update by using builders:
$update = new Pipeline( Stage::set(<field name>: <value>), Stage::set(<field name>: <value>), ... );
This example performs the following actions:
Uses the
Query::eq()
factory method to match documents in which thewatlev
field value is'partly submerged at high water'
Uses the
Stage::set()
method to set theyear
field to1870
Calls the
MongoDB\Collection::updateOne()
method to perform the updatePrints the number of updated documents
// Creates a query filter and an update document by // using builders and updates the first matching document $result = $collection->updateOne( Query::query(watlev: Query::eq('partly submerged at high water')), new Pipeline( Stage::set(year: 1870), ), ); // Prints number of updated documents echo 'Updated documents: ', $result->getModifiedCount(), PHP_EOL;
Updated documents: 1
Modify Change Stream Output
You can use factory methods from the Stage
class to modify a change
stream's output by creating a pipeline. To learn more about change
streams, see the Monitor Data Changes guide.
The following steps describe how to create a change stream filter by using builders:
Create an array.
Pass one or more
$match
stages by calling factory methods from theStage
class and the required parameters.
The following code shows the template to modify change stream output by using builders:
$pipeline = [ Stage::<factory method>(...), Stage::<factory method>(...), ... ];
You can pass this pipeline to the following methods:
This example performs the following actions:
Uses the
Stage::match()
method to filter for only change events for update operationsUses the
Stage::project()
method to output only theoperationType
,ns
(namespace), andfullDocument
fieldsCalls the
MongoDB\Collection::watch()
method to open the change stream and sets thefullDocument
option to output the full document after updatePrints change events as they occur
// Creates a pipeline to filter for update operations and return // only specific fields $pipeline = [ Stage::match(operationType: Query::eq('update')), Stage::project(operationType: 1, ns: 1, fullDocument: 1), ]; // Opens the change stream $changeStream = $collection->watch( $pipeline, ['fullDocument' => MongoDB\Operation\Watch::FULL_DOCUMENT_UPDATE_LOOKUP] ); // Prints change events based on the pipeline specifications for ($changeStream->rewind(); true; $changeStream->next()) { if (! $changeStream->valid()) { continue; } $event = $changeStream->current(); echo json_encode($event), PHP_EOL; if ($event['operationType'] === 'invalidate') { break; } }
{ "_id":..., "operationType":"update", "fullDocument":{"_id":...,"feature_type":"Wrecks - Visible",...}, "ns":{"db":"sample_geospatial","coll":"shipwrecks"} }
To learn more about the information provided by change events, see Change Events in the MongoDB Server manual.