Latest web development tutorials

MongoDB PHP

在php中使用mongodb你必須使用mongodb 的php驅動。

MongoDB PHP在各平台上的安裝及驅動包下載請查看: PHP安裝MongoDB擴展驅動

如果你使用的是PHP7,請參閱: PHP7 MongoDB安裝與使用

確保連接及選擇一個數據庫

為了確保正確連接,你需要指定數據庫名,如果數據庫在mongoDB中不存在,mongoDB會自動創建

代碼片段如下:

<?php
$m = new MongoClient(); // 连接默认主机和端口为:mongodb://localhost:27017
$db = $m->test; // 获取名称为 "test" 的数据库
?>

創建集合

創建集合的代碼片段如下:

<?php
$m = new MongoClient(); // 连接
$db = $m->test; // 获取名称为 "test" 的数据库
$collection = $db->createCollection("w3big");
echo "集合创建成功";
?>

執行以上程序,輸出結果如下:

集合创建成功

插入文檔

在mongoDB中使用insert() 方法插入文檔:

插入文檔代碼片段如下:

<?php
$m = new MongoClient();    // 连接到mongodb
$db = $m->test;            // 选择一个数据库
$collection = $db->w3big; // 选择集合
$document = array( 
	"title" => "MongoDB", 
	"description" => "database", 
	"likes" => 100,
	"url" => "http://www.w3big.com/mongodb/",
	"by", "本教程"
);
$collection->insert($document);
echo "数据插入成功";
?>

執行以上程序,輸出結果如下:

数据插入成功

然後我們在mongo客戶端使用db.w3big.find().pretty();命令查看數據:


查找文檔

使用find() 方法來讀取集合中的文檔。

讀取使用文檔的代碼片段如下:

<?php
$m = new MongoClient();    // 连接到mongodb
$db = $m->test;            // 选择一个数据库
$collection = $db->w3big; // 选择集合

$cursor = $collection->find();
// 迭代显示文档标题
foreach ($cursor as $document) {
	echo $document["title"] . "\n";
}
?>

執行以上程序,輸出結果如下:

MongoDB

更新文檔

使用update() 方法來更新文檔。

以下實例將更新文檔中的標題為' MongoDB 教程', 代碼片段如下:

<pre>
<?php
$m = new MongoClient();    // 连接到mongodb
$db = $m->test;            // 选择一个数据库
$collection = $db->w3big; // 选择集合
// 更新文档
$collection->update(array("title"=>"MongoDB"), array('$set'=>array("title"=>"MongoDB 教程")));
// 显示更新后的文档
$cursor = $collection->find();
// 循环显示文档标题
foreach ($cursor as $document) {
	echo $document["title"] . "\n";
}
?>

執行以上程序,輸出結果如下:

MongoDB 教程

然後我們在mongo客戶端使用db.w3big.find().pretty();命令查看數據:


刪除文檔

使用remove() 方法來刪除文檔。

以下實例中我們將移除'title' 為'MongoDB 教程' 的一條數據記錄。 , 代碼片段如下:

<?php
$m = new MongoClient();    // 连接到mongodb
$db = $m->test;            // 选择一个数据库
$collection = $db->w3big; // 选择集合
   
// 移除文档
$collection->remove(array("title"=>"MongoDB 教程"), array("justOne" => true));

// 显示可用文档数据
$cursor = $collection->find();
foreach ($cursor as $document) {
	echo $document["title"] . "\n";
}
?>

除了以上實例外,在php中你還可以使用findOne(), save(), limit(), skip(), sort()等方法來操作Mongodb數據庫。

更多的操作方法可以參考Mongodb核心類: http://php.net/manual/zh/mongo.core.php