-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphp-mongodb-crud-example.php
186 lines (139 loc) · 5.86 KB
/
php-mongodb-crud-example.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
<?php
// --------------------------------------------------------------------------------
// github.com/morebrackets/php-mongodb-crud-example
// No Copyright. Public Domain. Do anything you want with this code.
// This example code will get you started with the basics of PHP & MongoDB
// --------------------------------------------------------------------------------
$dbHost = 'localhost'; // DB Server Host - This could also be 127.0.0.1 or a remore host/ip
$dbPort = 27017; // DB Server Port
$dbName = 'testdb'; // Database where we will work
$dbColl = 'testcoll'; // Collection (like a table) where we will work
error_reporting(-1); // display all errors (not required)
// To install the MongoDB PHP driver:
// composer require mongodb/mongodb
// add extension=mongodb.so to php.ini
require_once 'vendor/autoload.php'; // Path to Composer's autoload which includes the MongoDB driver
// CONNECT
$mdbClient = new MongoDB\Client('mongodb://' . $dbHost . ':' . $dbPort);
try {
$dbs = $mdbClient->listDatabases();
} catch (MongoDB\Driver\Exception\ConnectionTimeoutException $e) {
echo "Error: PHP cannot connect to MongoDB<br>\n";
die();
}
// SELECT DB (shortcut for future reuse)
$DB = $mdbClient->{$dbName};
// DEFINE an INDEX (not required)
$DB->{$dbColl}->createIndex(['name' => 1]);
// CREATE (Insert one Document)
// Note, this will fail and kill the entire script if an indexed unique field already exists. Use find first or upsert instead if possible.
$result = $DB->{$dbColl}->insertOne(['name' => 'Peter Griffin', 'password' => 123, 'food' => 'Pizza', 'greeting' => 'Hello', 'age' => 35]);
echo "INSERTed MongoID '" . $result->getInsertedId() . "' (1)<br>\n";
$result = $DB->{$dbColl}->insertOne(['name' => 'Stewie Griffin', 'password' => 456, 'food' => 'Carrots', 'greeting' => 'Goodbye', 'age' => 2]);
echo "INSERTed MongoID '" . $result->getInsertedId() . "' (2)<br>\n";
// CREATE/UPDATE (Upsert one Document)
$result = $DB->{$dbColl}->updateOne(
['name' => 'Peter Griffin', 'password' => 123], // What document to find
[
'$set' => ['name' => 'Peter Griffin', 'password' => 456, 'food' => 'Avocado'], // What document keys to update/insert
'$unset' => ['a' => true,'b' => true], // Delete some keys
'$inc' => ['u' => 1] // Increment a key
],
['upsert' => true] // Enable upsert
);
if($result->getUpsertedCount()){
// AN INSERT WAS PERFORMED (No existing document found)
echo "Upsert: An INSERT was performed resulting in new MongoID '" . $result->getUpsertedId() . "'.<br>\n";
}else{
// AN UPDATE WAS PERFORMED (Document alreay existed)
// Note: You can run a new find command here to find the _id or use findAndModify instead of upsert
echo "Upsert: An UPDATE was performed.<br>\n";
}
// UPDATE (One Document)
$DB->{$dbColl}->updateOne(
['name' => 'Peter Griffin'],
['$set' => ['f' => 789]]
);
// Add to set (unique array)
$DB->{$dbColl}->updateOne(
['name' => 'Peter Griffin'],
[ '$addToSet' => [ 'color' => 'blue' ] ]
);
$DB->{$dbColl}->updateOne(
['name' => 'Peter Griffin'],
[ '$addToSet' => [ 'color' => 'green' ] ]
);
$DB->{$dbColl}->updateOne(
['name' => 'Peter Griffin'],
[ '$addToSet' => [ 'color' => 'pink' ] ]
);
// Add array items to set
$fruit = ['orange','grape','blueberry'];
$DB->{$dbColl}->updateOne(
['name' => 'Peter Griffin'],
[ '$addToSet' => [ 'color' => ['$each' => $fruit] ] ]
);
// Remove from array
$DB->{$dbColl}->updateOne(
['name' => 'Peter Griffin'],
[ '$pull' => [ 'color' => 'green' ] ]
);
// Update Many
$result = $collection->updateMany(
["name" => ["$exists" => true] ],
['$set' => ['hey' => 'you']]
);
echo "Update Many: ".$result->getModifiedCount()." document(s) modified.<br>\n";
// READ (Find One Document by name)
$doc = $DB->{$dbColl}->findOne(['name' => 'Peter Griffin']);
$doc['_id'] = (string)$doc['_id']; // Convert MongoID Object to a string so that json_encode works
echo "Read Document (1): " . json_encode($doc) . "<br>\n";
// Validate MongoID (format)
if(isValidMongoID($doc['_id'])){
echo "MongoID '".$doc['_id']."' is valid.<br>\n";
}else{
echo "MongoID '".$doc['_id']."' is NOT valid.<br>\n";
}
// READ (Find One Documents by _id object)
$doc = $DB->{$dbColl}->findOne(['_id' => $doc['_id'] ]);
$doc['_id'] = (string)$doc['_id']; // Convert MongoID Object to a string so that json_encode works
echo "Read Document (2): " . json_encode($doc) . "<br>\n";
// READ (Find One Documents by _id string)
$doc = $DB->{$dbColl}->findOne(['_id' => new MongoDB\BSON\ObjectId((string)$doc['_id']) ]);
$doc['_id'] = (string)$doc['_id']; // Convert MongoID Object to a string so that json_encode works
echo "Read Document (3): " . json_encode($doc) . "<br>\n";
// READ (Find One Document by largest value)
$doc = $DB->{$dbColl}->findOne(
[],
['sort' => ['age' => -1]]
);
echo "Read Document (4): " . json_encode($doc) . "<br>\n";
// READ (Find All Documents, don't return some fields, sort assending by n)
$cursor = $DB->{$dbColl}->find(
[],
[
'projection' => [
'password' => 0, // skip this field
'ssn' => 0, // skip this field
],
'sort' => ['name' => 1]
]
);
foreach ($cursor as $doc) {
$doc['_id'] = (string)$doc['_id']; // Convert MongoID Object to a string
echo "Read Document (5): " . json_encode($doc) . "<br>\n";
}
// COUNT number of Documents
$count = $DB->{$dbColl}->count();
echo "Count of Documents: " . $count . "<br>\n";
// DELETE One Document
$DB->{$dbColl}->deleteOne(['name' => 'Peter Griffin']);
/* Helper function to check if a string is a valid MongoID (24 char hex) */
function isValidMongoID($id){
if ($id instanceof \MongoDB\BSON\ObjectID || preg_match('/^[a-f\d]{24}$/i', $id)) {
return true;
}else{
return false;
}
}
?>