105.md 13.9 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10
# MongoDB PHP 教程

> 原文: [http://zetcode.com/db/mongodbphp/](http://zetcode.com/db/mongodbphp/)

在本教程中,我们将展示如何在 PHP 中使用 MongoDB。 我们将新的`mongodb`驱动程序用于 PHP。 在 ZetCode 上有一个简洁的 [PHP 教程](/lang/php/)

[Tweet](https://twitter.com/share) 

MongoDB 是 NoSQL 跨平台的面向文档的数据库。 它是可用的最受欢迎的数据库之一。 MongoDB 由 MongoDB Inc.开发,并作为免费和开源软件发布。

W
wizardforcel 已提交
11
MongoDB 中的 记录 是一个文档,它是由字段和值对组成的数据结构。 MongoDB 文档 与 JSON 对象相似。 字段的值可以包括其他文档,数组和文档数组。 MongoDB 将文档存储在 集合 中。 集合类似于关系数据库中的表,文档类似于行。
W
wizardforcel 已提交
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

## 安装 MongoDB

以下命令可用于在基于 Debian 的 Linux 上安装 MongoDB。

```
$ sudo apt-get install mongodb

```

该命令将安装 MongoDB 随附的必要软件包。

```
$ sudo service mongodb status
mongodb start/running, process 975

```

使用`sudo service mongodb status`命令,我们检查`mongodb`服务器的状态。

```
$ sudo service mongodb start
mongodb start/running, process 6448

```

`mongodb`服务器由`sudo service mongodb start`命令启动。

W
wizardforcel 已提交
40
## 建立数据库
W
wizardforcel 已提交
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

`mongo`工具是 MongoDB 的交互式 JavaScript Shell 界面,它为系统管理员提供了一个界面,并为开发人员提供了一种直接测试数据库查询和操作的方法。

```
$ mongo testdb
MongoDB shell version: 2.4.9
connecting to: testdb
> db
testdb
> db.cars.insert({name: "Audi", price: 52642})
> db.cars.insert({name: "Mercedes", price: 57127})
> db.cars.insert({name: "Skoda", price: 9000})
> db.cars.insert({name: "Volvo", price: 29000})
> db.cars.insert({name: "Bentley", price: 350000})
> db.cars.insert({name: "Citroen", price: 21000})
> db.cars.insert({name: "Hummer", price: 41400})
> db.cars.insert({name: "Volkswagen", price: 21600})

```

我们创建一个`testdb`数据库,并在`cars`集合中插入八个文档。

## 安装 PHP 驱动程序

有两种驱动程序可用:旧版`mongo`驱动程序和新版`mongodb`驱动程序。 在本教程中,我们将使用新的`mongodb`驱动程序。

接下来,我们展示如何手动安装 PHP MongoDB 驱动程序。

```
$ git clone https://github.com/mongodb/mongo-php-driver.git
$ cd mongo-php-driver
$ git submodule sync && git submodule update --init
$ phpize
$ ./configure
$ make 
$ sudo make install

```

我们下载源代码并从中安装驱动程序。

```
extension=mongodb.so

```

W
wizardforcel 已提交
87
我们将`mongodb.so`扩展名添加到`php.ini`文档中。
W
wizardforcel 已提交
88 89 90 91 92 93 94

## 数据库统计

第一个示例连接到`testdb`数据库并获取其统计信息。

`MongoDB\Driver\Manager`负责维护与 MongoDB 的连接。 `MongoDB\Driver\Command`表示数据库命令。 成功后,命令返回`MongoDB\Driver\Cursor`

W
wizardforcel 已提交
95
`dbstats.php`
W
wizardforcel 已提交
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 187 188

```
<?php

try {

    $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");

    $stats = new MongoDB\Driver\Command(["dbstats" => 1]);
    $res = $mng->executeCommand("testdb", $stats);

    $stats = current($res->toArray());

    print_r($stats);

} catch (MongoDB\Driver\Exception\Exception $e) {

    $filename = basename(__FILE__);

    echo "The $filename script has experienced an error.\n"; 
    echo "It failed with the following exception:\n";

    echo "Exception:", $e->getMessage(), "\n";
    echo "In file:", $e->getFile(), "\n";
    echo "On line:", $e->getLine(), "\n";       
}

?>

```

该示例连接到`testdb`数据库并执行`dbstats`命令。 它显示了一些数据库统计信息。

```
$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");

```

使用`MongoDB\Driver\Manager`类,我们连接到`testdb`数据库。 27017 是 MongoDB 服务器侦听的默认端口。

```
$res = $mng->executeCommand("testdb", $stats);

```

`MongoDB\Driver\Command`用于执行`dbstats`命令。

```
$stats = current($res->toArray());

```

`toArray()`方法返回一个数组,其中包含此游标的所有结果,`current()`函数返回该数组的当前元素。 在我们的例子中,数组只有一个元素。

```
print_r($stats);

```

`print_r()`函数打印`$stats`变量的人类可读表示。

```
$ php dbstats.php 
stdClass Object
(
    [db] => testdb
    [collections] => 3
    [objects] => 12
    [avgObjSize] => 52.666666666667
    [dataSize] => 632
    [storageSize] => 12288
    [numExtents] => 3
    [indexes] => 1
    [indexSize] => 8176
    [fileSize] => 201326592
    [nsSizeMB] => 16
    [dataFileVersion] => stdClass Object
        (
            [major] => 4
            [minor] => 5
        )

    [ok] => 1
)

```

这是`dbstats.php`程序的输出。

## 列出数据库

`listDatabases`命令提供所有现有数据库的列表。

W
wizardforcel 已提交
189
`list_databases.php`
W
wizardforcel 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

```
<?php

try {

    $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");

    $listdatabases = new MongoDB\Driver\Command(["listDatabases" => 1]);
    $res = $mng->executeCommand("admin", $listdatabases);

    $databases = current($res->toArray());

    foreach ($databases->databases as $el) {

        echo $el->name . "\n";
    }

} catch (MongoDB\Driver\Exception\Exception $e) {

    $filename = basename(__FILE__);

    echo "The $filename script has experienced an error.\n"; 
    echo "It failed with the following exception:\n";

    echo "Exception:", $e->getMessage(), "\n";
    echo "In file:", $e->getFile(), "\n";
    echo "On line:", $e->getLine(), "\n";       
}

?>

```

该示例在 MongoDB 中打印可用的数据库。

```
$listdatabases = new MongoDB\Driver\Command(["listDatabases" => 1]);
$res = $mng->executeCommand("admin", $listdatabases);

```

我们执行`listDatabases`命令。 该命令在`admin`数据库上执行。

```
$databases = current($res->toArray());

```

该命令返回单个结果文档,其中包含`databases`数组字段中所有数据库的信息。

```
foreach ($databases->databases as $el) {

    echo $el->name . "\n";
}

```

我们遍历数据库数组并打印可用数据库的名称。

```
$ php list_databases.php 
testdb
test
local

```

在本地计算机上,我们具有这三个数据库。

## 读取数据

`MongoDB\Driver\Query`是代表数据库查询的值对象。

W
wizardforcel 已提交
265
`read_all.php`
W
wizardforcel 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338

```
<?php

try {

    $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    $query = new MongoDB\Driver\Query([]); 

    $rows = $mng->executeQuery("testdb.cars", $query);

    foreach ($rows as $row) {

        echo "$row->name : $row->price\n";
    }

} catch (MongoDB\Driver\Exception\Exception $e) {

    $filename = basename(__FILE__);

    echo "The $filename script has experienced an error.\n"; 
    echo "It failed with the following exception:\n";

    echo "Exception:", $e->getMessage(), "\n";
    echo "In file:", $e->getFile(), "\n";
    echo "On line:", $e->getLine(), "\n";       
}

?>

```

该示例从`testdb.cars`集合读取所有数据。

```
$query = new MongoDB\Driver\Query([]); 

```

创建一个`MongoDB\Driver\Query`对象。 如果我们传递一个空数组,它将读取所有数据。

```
$rows = $mng->executeQuery("testdb.cars", $query);

```

`executeQuery()`执行查询。 第一个参数是集合名称,第二个参数是查询。

```
foreach ($rows as $row) {

    echo "$row->name : $row->price\n";
}

```

我们遍历所有匹配的文档。

```
$ php read_all.php 
Audi : 52642
Mercedes : 57127
Skoda : 9000
Volvo : 29000
Bentley : 350000
Citroen : 21000
Hummer : 41400
Volkswagen : 21600

```

这是`read_all.php`脚本的输出。

W
wizardforcel 已提交
339
## 筛选数据
W
wizardforcel 已提交
340 341 342

`MongoDB\Driver\Query`包含用于过滤数据的过滤参数。

W
wizardforcel 已提交
343
`filtering.php`
W
wizardforcel 已提交
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419

```
<?php

try {

    $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");

    $filter = [ 'name' => 'Volkswagen' ]; 
    $query = new MongoDB\Driver\Query($filter);     

    $res = $mng->executeQuery("testdb.cars", $query);

    $car = current($res->toArray());

    if (!empty($car)) {

        echo $car->name, ": ", $car->price, PHP_EOL;
    } else {

        echo "No match found\n";
    }

} catch (MongoDB\Driver\Exception\Exception $e) {

    $filename = basename(__FILE__);

    echo "The $filename script has experienced an error.\n"; 
    echo "It failed with the following exception:\n";

    echo "Exception:", $e->getMessage(), "\n";
    echo "In file:", $e->getFile(), "\n";
    echo "On line:", $e->getLine(), "\n";    
}

?>

```

该示例搜索大众汽车的价格。

```
$filter = [ 'name' => 'Volkswagen' ]; 
$query = new MongoDB\Driver\Query($filter); 

```

我们将过滤器参数提供给`MongoDB\Driver\Query`

```
$car = current($res->toArray());

if (!empty($car)) {

    echo $car->name, ": ", $car->price, PHP_EOL;
} else {

    echo "No match found\n";
}

```

我们会打印所选汽车的名称和价格。 我们使用`empty()`函数确保返回的变量不为空。

```
$ php filtering.php 
Volkswagen: 21600

```

这是`filtering.php`脚本的输出。

## 投影

投影可用于指定应返回哪些字段。

W
wizardforcel 已提交
420
`projection.php`
W
wizardforcel 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493

```
<?php

try {

    $filter = [];
    $options = ["projection" => ['_id' => 0]];

    $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    $query = new MongoDB\Driver\Query($filter, $options);

    $rows = $mng->executeQuery("testdb.cars", $query);

    foreach ($rows as $row) {

           print_r($row);
    }    

} catch (MongoDB\Driver\Exception\Exception $e) {

    $filename = basename(__FILE__);

    echo "The $filename script has experienced an error.\n"; 
    echo "It failed with the following exception:\n";

    echo "Exception:", $e->getMessage(), "\n";
    echo "In file:", $e->getFile(), "\n";
    echo "On line:", $e->getLine(), "\n";    
}

?>

```

在示例中,我们隐藏了第一个字段`_id`

```
$options = ["projection" => ['_id' => 0]];

```

投影以`projection`数组指定。 在这里,我们隐藏`_id`字段。

```
$query = new MongoDB\Driver\Query($filter, $options);     

```

投影在`MongoDB\Driver\Query`的第二个参数中传递。

```
$ php projection.php 
stdClass Object
(
    [name] => Audi
    [price] => 52642
)
stdClass Object
(
    [name] => Mercedes
    [price] => 57127
)
...

```

这是`projection.php`脚本的部分输出。 仅返回名称和价格字段。

## 限制数据输出

`limit`查询选项指定要返回的文档数,`sort`选项指定排序顺序。

W
wizardforcel 已提交
494
`read_limit.php`
W
wizardforcel 已提交
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551

```
<?php

try {

    $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    $query = new MongoDB\Driver\Query([], ['sort' => [ 'name' => 1], 'limit' => 5]);     

    $rows = $mng->executeQuery("testdb.cars", $query);

    foreach ($rows as $row) {

        echo "$row->name : $row->price\n";
    }

} catch (MongoDB\Driver\Exception\Exception $e) {

    $filename = basename(__FILE__);

    echo "The $filename script has experienced an error.\n"; 
    echo "It failed with the following exception:\n";

    echo "Exception:", $e->getMessage(), "\n";
    echo "In file:", $e->getFile(), "\n";
    echo "On line:", $e->getLine(), "\n";       
}

?>

```

该示例从`testdb.cars`集合中读取所有数据,将输出限制为五辆汽车,并按照汽车名称升序排序。

```
$query = new MongoDB\Driver\Query([], ['sort' => [ 'name' => 1], 'limit' => 5]); 

```

我们在查询的第二个参数中指定`sort``limit`选项。

```
$ php read_limit.php 
Audi : 52642
Bentley : 350000
Citroen : 21000
Hummer : 41400
Mercedes : 57127

```

这是`read_limit.php`脚本的输出。

## 批量写入

`MongoDB\Driver\Manager::executeBulkWrite`方法执行一个或多个写操作,包括插入,更新和删除。

W
wizardforcel 已提交
552
`bulkwrite.php`
W
wizardforcel 已提交
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645

```
<?php

try {

    $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");

    $bulk = new MongoDB\Driver\BulkWrite;

    $doc = ['_id' => new MongoDB\BSON\ObjectID, 'name' => 'Toyota', 'price' => 26700];
    $bulk->insert($doc);
    $bulk->update(['name' => 'Audi'], ['$set' => ['price' => 52000]]);
    $bulk->delete(['name' => 'Hummer']);

    $mng->executeBulkWrite('testdb.cars', $bulk);

} catch (MongoDB\Driver\Exception\Exception $e) {

    $filename = basename(__FILE__);

    echo "The $filename script has experienced an error.\n"; 
    echo "It failed with the following exception:\n";

    echo "Exception:", $e->getMessage(), "\n";
    echo "In file:", $e->getFile(), "\n";
    echo "On line:", $e->getLine(), "\n";    
}

?>

```

该脚本会插入一辆新车,更新一辆车,然后删除一辆车。

```
$bulk = new MongoDB\Driver\BulkWrite();

```

`MongoDB\Driver\BulkWrite`收集一个或多个应发送到服务器的写操作。

```
$doc = ['_id' => new MongoDB\BSON\ObjectID, 'name' => 'Toyota', 'price' => 26700];

```

这是要插入的新文档。 `MongoDB\BSON\ObjectID`生成一个新的 ObjectId。 它是用于唯一标识集合中文档的值。

```
$bulk->insert($doc);

```

使用`insert()`方法创建一个插入操作。

```
$bulk->update(['name' => 'Audi'], ['$set' => ['price' => 52000]]);

```

使用`update()`方法创建更新操作。 `$set`运算符将字段的值替换为指定的值。

```
$bulk->delete(['name' => 'Hummer']);

```

使用`delete()`方法创建删除操作。

```
$mng->executeBulkWrite('testdb.cars', $bulk);

```

`executeBulkWrite()``testdb.cars`集合执行三个操作。

```
> db.cars.find()
{ "_id" : ObjectId("571e05a6c4a3bc7dc758b457"), "name" : "Audi", "price" : 52000 }
{ "_id" : ObjectId("571e05b5c4a3bc7dc758b458"), "name" : "Mercedes", "price" : 57127 }
{ "_id" : ObjectId("571e05bec4a3bc7dc758b459"), "name" : "Skoda", "price" : 9000 }
{ "_id" : ObjectId("571e05c7c4a3bc7dc758b45a"), "name" : "Volvo", "price" : 29000 }
{ "_id" : ObjectId("571e05d0c4a3bc7dc758b45b"), "name" : "Bentley", "price" : 350000 }
{ "_id" : ObjectId("571e05e0c4a3bc7dc758b45c"), "name" : "Citroen", "price" : 21000 }
{ "_id" : ObjectId("571e05fcc4a3bc7dc758b45e"), "name" : "Volkswagen", "price" : 21600 }
{ "_id" : ObjectId("5720a4e581365b0e9414d0e1"), "name" : "Toyota", "price" : 26700 }

```

使用`mongo`工具确认更改。

在本教程中,我们使用了 MongoDB 和 PHP。