Skip to content

Commit 3ea080a

Browse files
committed
Merge remote-tracking branch 'upstream/php-standardization' into DOCSP-41967-insert
2 parents 519dc41 + 017275c commit 3ea080a

File tree

15 files changed

+1283
-3
lines changed

15 files changed

+1283
-3
lines changed

snooty.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,5 +26,6 @@ php-library = "MongoDB PHP Library"
2626
[constants]
2727
php-library = "MongoDB PHP Library"
2828
driver-short = "PHP library"
29+
stable-api = "Stable API"
2930
mdb-server = "MongoDB Server"
3031
api = "https://www.mongodb.com/docs/php-library/current/reference"

source/connect/connection-targets.txt

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
.. _php-connection-targets:
2+
3+
==========================
4+
Choose a Connection Target
5+
==========================
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: connection string, URI, server, settings, client, stable api
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 2
18+
:class: singlecol
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use a connection string and ``MongoDB\Client`` object
24+
to connect to different types of MongoDB deployments.
25+
26+
.. _php-connection-atlas:
27+
28+
Atlas
29+
-----
30+
31+
To connect to a MongoDB deployment on Atlas, include the following elements
32+
in your connection string:
33+
34+
- URI of your Atlas cluster
35+
- Database username
36+
- Database user's password
37+
38+
Then, pass your connection string to the ``MongoDB\Client`` constructor.
39+
40+
When you connect to Atlas, we recommend using the {+stable-api+} client option to avoid
41+
breaking changes when Atlas upgrades to a new version of {+mdb-server+}.
42+
To learn more about the {+stable-api+} feature, see the :ref:`{+stable-api+} page
43+
<php-stable-api>`.
44+
45+
The following code shows how to use the {+driver-short+} to connect to an Atlas cluster.
46+
The code also uses the ``serverApi`` option to specify a {+stable-api+} version.
47+
48+
.. literalinclude:: /includes/connect/atlas.php
49+
:copyable: true
50+
:language: php
51+
52+
.. tip::
53+
54+
Follow the :ref:`php-connection-string` step of the Quick Start
55+
to retrieve your connection string.
56+
57+
.. _php-connection-local:
58+
59+
Local Deployments
60+
-----------------
61+
62+
To connect to a local MongoDB deployment, use ``localhost`` as the hostname. By
63+
default, the ``mongod`` process runs on port 27017, though you can customize this for
64+
your deployment.
65+
66+
The following code shows how to use the {+driver-short+} to connect to a local MongoDB
67+
deployment:
68+
69+
.. literalinclude:: /includes/connect/client.php
70+
:language: php
71+
:copyable: true
72+
73+
.. _php-connection-replica-set:
74+
75+
Replica Sets
76+
------------
77+
78+
To connect to a replica set, specify the hostnames (or IP addresses) and
79+
port numbers of the replica set members in your connection string.
80+
81+
If you aren't able to provide a full list of hosts in the replica set, you can
82+
specify one or more of the hosts in the replica set and instruct the {+driver-short+} to
83+
perform automatic discovery to find the others. To instruct the driver to perform
84+
automatic discovery, choose one of the following actions:
85+
86+
- Specify the name of the replica set as the value of the ``replicaSet`` parameter.
87+
- Specify ``false`` as the value of the ``directConnection`` parameter.
88+
- Specify more than one host in the replica set.
89+
90+
In the following example, the driver uses a sample connection URI to connect to the
91+
MongoDB replica set ``sampleRS``, which is running on port ``27017`` of three different
92+
hosts, including ``host1``:
93+
94+
.. literalinclude:: /includes/connect/replica-set.php
95+
:language: php
96+
:copyable: true
97+
98+
Initialization
99+
~~~~~~~~~~~~~~
100+
101+
To initialize a replica set, you must connect directly to a single member. To do so,
102+
set the ``directConnection`` connection
103+
option to ``true`` in the connection string. The following code example shows how to
104+
set this connection option:
105+
106+
.. literalinclude:: /includes/connect/direct-connection.php
107+
:language: php
108+
:copyable: true
109+
110+
API Documentation
111+
-----------------
112+
113+
To learn more about using the ``MongoDB\Client`` class,
114+
see the following API documentation:
115+
116+
- :ref:`MongoDB\Client <php-api-mongodbclient>`

source/includes/connect/atlas.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
// Replace the placeholder with your Atlas connection string
4+
$uri = "<connection string>";
5+
6+
// Create a MongoDB client with server API options
7+
$client = new MongoDB\Client($uri, [], [
8+
'serverApi' => new MongoDB\Driver\ServerApi('1')
9+
]);
10+
11+
// Ping the server to verify that the connection works
12+
$admin = $client->admin;
13+
$command = new MongoDB\Driver\Command(['ping' => 1]);
14+
$result = $admin->command($command)->toArray();
15+
16+
echo json_encode($result), "\n";
17+
echo "Pinged your deployment. You successfully connected to MongoDB!\n";
18+
19+
?>
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<?php
2+
3+
// Replace the placeholders with your actual hostname and port
4+
$uri = "mongodb://<hostname>:<port>/?directConnection=true";
5+
6+
// Create a MongoDB client
7+
$client = new MongoDB\Client($uri);
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?php
2+
3+
$uri = "mongodb://host1:27017/?replicaSet=sampleRS";
4+
5+
// Create a MongoDB client
6+
$client = new MongoDB\Client($uri);
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
<?php
2+
require 'vendor/autoload.php';
3+
4+
// start-to-json
5+
function toJSON(object $document): string
6+
{
7+
return MongoDB\BSON\Document::fromPHP($document)->toRelaxedExtendedJSON();
8+
}
9+
// end-to-json
10+
11+
$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset');
12+
$client = new MongoDB\Client($uri);
13+
14+
// start-db-coll
15+
$collection = $client->sample_restaurants->restaurants;
16+
// end-db-coll
17+
18+
// Monitors and prints changes to the "restaurants" collection
19+
// start-open-change-stream
20+
$changeStream = $collection->watch();
21+
22+
for ($changeStream->rewind(); true; $changeStream->next()) {
23+
if ( ! $changeStream->valid()) {
24+
continue;
25+
}
26+
$event = $changeStream->current();
27+
echo toJSON($event) . PHP_EOL;
28+
29+
if ($event['operationType'] === 'invalidate') {
30+
break;
31+
}
32+
}
33+
// end-open-change-stream
34+
35+
// Updates a document that has a "name" value of "Blarney Castle"
36+
// start-update-for-change-stream
37+
$result = $collection->updateOne(
38+
['name' => 'Blarney Castle'],
39+
['$set' => ['cuisine' => 'Irish']]
40+
);
41+
// end-update-for-change-stream
42+
43+
// Passes a pipeline argument to watch() to monitor only update operations
44+
// start-change-stream-pipeline
45+
$pipeline = [['$match' => ['operationType' => 'update']]];
46+
$changeStream = $collection->watch($pipeline);
47+
48+
for ($changeStream->rewind(); true; $changeStream->next()) {
49+
if ( ! $changeStream->valid()) {
50+
continue;
51+
}
52+
$event = $changeStream->current();
53+
echo toJSON($event) . PHP_EOL;
54+
55+
if ($event['operationType'] === 'invalidate') {
56+
break;
57+
}
58+
}
59+
// end-change-stream-pipeline
60+
61+
// Passes an options argument to watch() to include the post-image of updated documents
62+
// start-change-stream-post-image
63+
$options = ['fullDocument' => MongoDB\Operation\Watch::FULL_DOCUMENT_UPDATE_LOOKUP];
64+
$changeStream = $collection->watch([], $options);
65+
66+
for ($changeStream->rewind(); true; $changeStream->next()) {
67+
if ( ! $changeStream->valid()) {
68+
continue;
69+
}
70+
$event = $changeStream->current();
71+
echo toJSON($event) . PHP_EOL;
72+
73+
if ($event['operationType'] === 'invalidate') {
74+
break;
75+
}
76+
}
77+
// end-change-stream-post-image
78+

source/includes/read/count.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
require 'vendor/autoload.php';
3+
4+
use MongoDB\BSON\Document;
5+
6+
$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset');
7+
$client = new MongoDB\Client($uri);
8+
9+
// start-db-coll
10+
$collection = $client->sample_training->companies;
11+
// end-db-coll
12+
13+
// Counts all documents in the collection
14+
// start-count-all
15+
$result = $collection->countDocuments([]);
16+
echo "Number of documents: " . $result;
17+
// end-count-all
18+
19+
// Counts documents that have a "founded_year" value of 2010
20+
// start-count-accurate
21+
$result = $collection->countDocuments(['founded_year' => 2010]);
22+
echo "Number of companies founded in 2010: " . $result;
23+
// end-count-accurate
24+
25+
// Counts a maximum of 100 documents that have a "number_of_employees" value of 50
26+
// start-modify-accurate
27+
$result = $collection->countDocuments(
28+
['number_of_employees' => 50],
29+
['limit' => 100]
30+
);
31+
echo "Number of companies with 50 employees: " . $result;
32+
// end-modify-accurate
33+
34+
// Estimates the number of documents in the collection
35+
// start-count-estimate
36+
$result = $collection->estimatedDocumentCount();
37+
echo "Estimated number of documents: " . $result;
38+
// end-count-estimate
39+
40+
// Estimates the number of documents in the collection and sets a time limit on the operation
41+
// start-modify-estimate
42+
$result = $collection->estimatedDocumentCount(['maxTimeMS' => 1000]);
43+
echo "Estimated number of documents: " . $result;
44+
// end-modify-estimate

source/includes/read/distinct.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
require 'vendor/autoload.php';
3+
4+
use MongoDB\BSON\Document;
5+
6+
$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset');
7+
$client = new MongoDB\Client($uri);
8+
9+
// start-db-coll
10+
$collection = $client->sample_restaurants->restaurants;
11+
// end-db-coll
12+
13+
// Retrieves distinct values of the "borough" field
14+
// start-distinct
15+
$results = $collection->distinct('borough', []);
16+
foreach ($results as $value) {
17+
echo json_encode($value) . PHP_EOL;
18+
}
19+
// end-distinct
20+
21+
// Retrieves distinct "borough" field values for documents with a "cuisine" value of "Italian"
22+
// start-distinct-with-query
23+
$results = $collection->distinct('borough', ['cuisine' => 'Italian']);
24+
foreach ($results as $value) {
25+
echo json_encode($value) . PHP_EOL;
26+
}
27+
// end-distinct-with-query
28+
29+
// Retrieves distinct "name" field values for documents matching the "borough" and "cuisine" fields query
30+
// and attaches a comment to the operation
31+
// start-distinct-with-comment
32+
$query = ['borough' => 'Bronx', 'cuisine' => 'Pizza'];
33+
$options = ['comment' => 'Bronx pizza restaurants'];
34+
$results = $collection->distinct('name', $query, $options);
35+
36+
foreach ($results as $value) {
37+
echo json_encode($value) . PHP_EOL;
38+
}
39+
// end-distinct-with-comment
40+

source/includes/write/update.php

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
require 'vendor/autoload.php';
4+
5+
$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset');
6+
$client = new MongoDB\Client($uri);
7+
8+
// start-db-coll
9+
$collection = $client->sample_restaurants->restaurants;
10+
// end-db-coll
11+
12+
// Updates the "name" value of a document from "Bagels N Buns" to "2 Bagels 2 Buns"
13+
// start-update-one
14+
$result = $collection->updateOne(
15+
['name' => 'Bagels N Buns'],
16+
['$set' => ['name' => '2 Bagels 2 Buns']]
17+
);
18+
// end-update-one
19+
20+
// Updates the "cuisine" value of documents from "Pizza" to "Pasta"
21+
// start-update-many
22+
$result = $collection->updateMany(
23+
['cuisine' => 'Pizza'],
24+
['$set' => ['cuisine' => 'Pasta']]
25+
);
26+
// end-update-many
27+
28+
// Updates the "borough" value of matching documents and inserts a document if none match
29+
// start-update-options
30+
$result = $collection->updateMany(
31+
['borough' => 'Manhattan'],
32+
['$set' => ['borough' => 'Manhattan (north)']],
33+
['upsert' => true]
34+
);
35+
// end-update-options
36+
37+
// Updates the "name" value of matching documents and prints the number of updates
38+
// start-update-result
39+
$result = $collection->updateMany(
40+
['name' => 'Dunkin\' Donuts'],
41+
['$set' => ['name' => 'Dunkin\'']]
42+
);
43+
echo 'Modified documents: ' . $result->getModifiedCount();
44+
// end-update-result
45+

source/read.txt

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,11 @@ Read Data from MongoDB
77
.. toctree::
88
:titlesonly:
99
:maxdepth: 1
10-
10+
1111
/read/retrieve
12+
/read/project
13+
/read/count
1214
/read/specify-documents-to-return
1315
/read/specify-a-query
14-
/read/project
16+
/read/distinct
17+
/read/change-streams

0 commit comments

Comments
 (0)