《MongoDB PHP》要點(diǎn):
本文介紹了MongoDB PHP,希望對(duì)您有用。如果有疑問(wèn),可以聯(lián)系我們。
相關(guān)主題:非關(guān)系型數(shù)據(jù)庫(kù)
維易PHP培訓(xùn)學(xué)院每天發(fā)布《MongoDB PHP》等實(shí)戰(zhàn)技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培養(yǎng)人才。
在php中使用mongodb你必需使用 mongodb 的 php驅(qū)動(dòng).
確保銜接及選擇一個(gè)數(shù)據(jù)庫(kù)
為了確保正確連接,你必要指定數(shù)據(jù)庫(kù)名,如果數(shù)據(jù)庫(kù)在mongoDB中不存在,mongoDB會(huì)自動(dòng)創(chuàng)建
代碼片段如下:
<?php
$m = new MongoClient(); // 銜接默認(rèn)主機(jī)和端口為:mongodb://localhost:27017$db = $m->test; // 獲取名稱(chēng)為 "test" 的數(shù)據(jù)庫(kù)?>
創(chuàng)立集合
創(chuàng)立集合的代碼片段如下:
<?php
$m = new MongoClient(); // 連接$db = $m->test; // 獲取名稱(chēng)為 "test" 的數(shù)據(jù)庫(kù)$collection = $db->createCollection("runoob");echo "集合創(chuàng)建勝利";?>
執(zhí)行以上程序,輸出成果如下:
集合創(chuàng)建勝利
插入文檔
在mongoDB中使用 insert() 辦法插入文檔:
插入文檔代碼片段如下:
<?php
$m = new MongoClient(); // 連接到mongodb$db = $m->test; // 選擇一個(gè)數(shù)據(jù)庫(kù)$collection = $db->runoob; // 選擇聚攏$document = array(
"title" => "MongoDB",
"description" => "database",
"likes" => 100,
"url" => "http://www.runoob.com/mongodb/",
"by", "菜鳥(niǎo)教程");$collection->insert($document);echo "數(shù)據(jù)插入勝利";?>
執(zhí)行以上程序,輸出成果如下:
數(shù)據(jù)插入勝利
然后我們?cè)?mongo 客戶(hù)端使用 db.runoob.find().pretty(); 命令查看數(shù)據(jù):
查找文檔
使用find() 辦法來(lái)讀取集合中的文檔.
讀取使用文檔的代碼片段如下:
<?php
$m = new MongoClient(); // 連接到mongodb$db = $m->test; // 選擇一個(gè)數(shù)據(jù)庫(kù)$collection = $db->runoob; // 選擇集合$cursor = $collection->find();// 迭代顯示文檔題目foreach ($cursor as $document) {
echo $document["title"] . "\n";}?>
執(zhí)行以上程序,輸出成果如下:
MongoDB
更新文檔
使用 update() 辦法來(lái)更新文檔.
以下實(shí)例將更新文檔中的題目為' MongoDB 教程', 代碼片段如下:
<pre><?php
$m = new MongoClient(); // 連接到mongodb$db = $m->test; // 選擇一個(gè)數(shù)據(jù)庫(kù)$collection = $db->runoob; // 選擇集合// 更新文檔$collection->update(array("title"=>"MongoDB"), array('$set'=>array("title"=>"MongoDB 教程")));// 顯示更新后的文檔$cursor = $collection->find();// 循環(huán)顯示文檔題目foreach ($cursor as $document) {
echo $document["title"] . "\n";}?>
執(zhí)行以上程序,輸出成果如下:
MongoDB 教程
然后我們?cè)?mongo 客戶(hù)端使用 db.runoob.find().pretty(); 命令查看數(shù)據(jù):
刪除文檔
使用 remove() 辦法來(lái)刪除文檔.
以下實(shí)例中我們將移除 'title' 為 'MongoDB 教程' 的一條數(shù)據(jù)記載., 代碼片段如下:
<?php
$m = new MongoClient(); // 連接到mongodb$db = $m->test; // 選擇一個(gè)數(shù)據(jù)庫(kù)$collection = $db->runoob; // 選擇聚攏
// 移除文檔$collection->remove(array("title"=>"MongoDB 教程"), array("justOne" => true));// 顯示可用文檔數(shù)據(jù)$cursor = $collection->find();foreach ($cursor as $document) {
echo $document["title"] . "\n";}?>
除了以上實(shí)例外,在php中你還可以使用findOne(), save(), limit(), skip(), sort()等辦法來(lái)操作Mongodb數(shù)據(jù)庫(kù).
更多的操作辦法可以參考 Mongodb 核心類(lèi):http://php.net/manual/zh/mongo.core.php.
如您還有不明確的可以在下面與我留言或是與我探討QQ群308855039,我們一起飛!
轉(zhuǎn)載請(qǐng)注明本頁(yè)網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/10221.html