File tree Expand file tree Collapse file tree 3 files changed +84
-1
lines changed Expand file tree Collapse file tree 3 files changed +84
-1
lines changed Original file line number Diff line number Diff line change @@ -20,4 +20,5 @@ Get Started with the PHP Library
20
20
21
21
.. toctree::
22
22
23
- /get-started/create-a-deployment/
23
+ /get-started/create-a-deployment/
24
+ /get-started/connect-to-mongodb/
Original file line number Diff line number Diff line change
1
+ .. _php-connect-to-mongodb:
2
+
3
+ ==================
4
+ Connect to MongoDB
5
+ ==================
6
+
7
+ .. facet::
8
+ :name: genre
9
+ :values: tutorial
10
+
11
+ .. meta::
12
+ :keywords: test connection, runnable, code example
13
+
14
+ .. procedure::
15
+ :style: connected
16
+
17
+ .. step:: Edit your PHP application file
18
+
19
+ Copy and paste the following code into the ``quickstart.php`` file, which queries
20
+ the ``movies`` collection in the ``sample_mflix`` database:
21
+
22
+ .. literalinclude:: /includes/get-started/quickstart.php
23
+
24
+ .. step:: Assign the connection string
25
+
26
+ Replace the ``<connection string>`` placeholder with the
27
+ connection string that you copied from the :ref:`php-connection-string`
28
+ step of this guide.
29
+
30
+ .. step:: Run your PHP application
31
+
32
+ In your project directory, run the following shell command to run the application:
33
+
34
+ .. code-block:: bash
35
+
36
+ php quickstart.php
37
+
38
+ The command line output contains details about the retrieved movie
39
+ document:
40
+
41
+ .. code-block:: none
42
+ :copyable: false
43
+
44
+ {
45
+ "_id": {
46
+ "$oid": "..."
47
+ },
48
+ ...
49
+ "rated": "R",
50
+ "metacritic": 80,
51
+ "title": "The Shawshank Redemption",
52
+ ...
53
+ }
54
+
55
+ If you encounter an error or see no output, ensure that you specified the
56
+ proper connection string in the ``quickstart.cpp`` file and that you loaded the
57
+ sample data.
58
+
59
+ After you complete these steps, you have a working application that
60
+ uses the {+php-library+} to connect to your MongoDB deployment, runs a query on
61
+ the sample data, and prints out the result.
62
+
63
+ .. include:: /includes/get-started/troubleshoot.rst
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ require __DIR__ . '/../vendor/autoload.php ' ;
4
+
5
+ use MongoDB \Client ;
6
+
7
+ $ client = new Client ('<connection string> ' );
8
+ $ db = $ client ->sample_mflix ;
9
+ $ collection = $ db ->movies ;
10
+
11
+ $ filter = ['title ' => 'The Shawshank Redemption ' ];
12
+ $ result = $ collection ->findOne ($ filter );
13
+
14
+ if ($ result ) {
15
+ echo json_encode ($ result , JSON_PRETTY_PRINT );
16
+ } else {
17
+ echo "Document not found " ;
18
+ }
19
+ ?>
You can’t perform that action at this time.
0 commit comments