Docs Menu
Docs Home
/ / /
PHP Library Manual

Operations with Builders

On this page

  • Overview
  • Sample Data
  • Import Builder Classes
  • Create a Filter
  • Retrieve Example
  • Delete Example
  • Define an Update Document
  • Modify Change Stream Output

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:

  • Create a Filter

  • Define an Update Document

  • Modify Change Stream Output

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.

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.

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;

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:

  1. Call the Query::query() method to create a query.

  2. 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.

This example performs the following actions:

  • Uses the Query::eq() factory method to match documents in which the feature_type field value is 'Wrecks - Visible'

  • Uses the Query::near() factory method to match documents in which the coordinates location field is within 10000 meters of the specified coordinates

  • Calls the MongoDB\Collection::find() method to retrieve the matching documents

  • Prints 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.

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 the feature_type field value contains the string 'nondangerous'

    • Clause that uses the Query::gt() factory method to check if the depth field value is greater than 10.0

  • Calls the MongoDB\Collection::deleteOne() method to delete the first matching document

  • Prints 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.

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:

  1. Create a Pipeline instance.

  2. Pass one or more stages by calling methods from the Stage class such as Stage::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 the watlev field value is 'partly submerged at high water'

  • Uses the Stage::set() method to set the year field to 1870

  • Calls the MongoDB\Collection::updateOne() method to perform the update

  • Prints 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

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:

  1. Create an array.

  2. Pass one or more $match stages by calling factory methods from the Stage 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 operations

  • Uses the Stage::project() method to output only the operationType, ns (namespace), and fullDocument fields

  • Calls the MongoDB\Collection::watch() method to open the change stream and sets the fullDocument option to output the full document after update

  • Prints 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.

Back

Store Large Files