時間:2024-03-26 14:39作者:下載吧人氣:34
MongoDB 是一種非關(guān)系型數(shù)據(jù)庫,具有更高的性能 比相比于關(guān)系型數(shù)據(jù)庫,文檔型的 MongoDB 能夠更好的存儲對象,MongoDB與PHP相結(jié)合也受到大家的歡迎。本文將介紹如何用 PHP 操作 MongoDB,并實(shí)現(xiàn)基本的增刪改查,供參考。
首先安裝安裝 PHP 操作 MongoDB 的第三方擴(kuò)展 MongoDB 并安裝 Drupal 8,可以利用模塊 Mongo DB 來安裝擴(kuò)展包。安裝:
1.登錄系統(tǒng),搜索 MongoDB 模塊,選擇 MongoDB,點(diǎn)擊 Install 按鈕;
2.將 MongoDB 模塊安裝至指定目錄;
3.進(jìn)入 php.ini 文件,添加 extension=’mongo.so’;
4.重啟 web 服務(wù)器,完成安裝。
安裝完成后,就可以開始操作 MongoDB 了, 以 php 語言為例:
1.連接 MongoDB 數(shù)據(jù)庫:
$m = new MongoDBDriverManager(“mongodb://localhost:27017”);
2.查詢數(shù)據(jù):
$filter = [‘name’ => ‘john’];
$query = new MongoDBDriverQuery($filter);
$cursor = $m->executeQuery(‘testdb.collection’, $query);
foreach ($cursor as $document) {
var_dump($document);
}
3.新增數(shù)據(jù):
$bulk = new MongoDBDriverBulkWrite;
$document = [‘name’ => ‘john’, ‘age’ => 30];
$bulk->insert($document);
$m->executeBulkWrite(‘testdb.collection’, $bulk);
4.修改數(shù)據(jù):
$bulk = new MongoDBDriverBulkWrite;
$filter = [‘name’ => ‘john’];
$newObj = [‘name’ => ‘john’, ‘age’ => 25];
$bulk->update($filter, $newObj);
$m->executeBulkWrite(‘testdb.collection’, $bulk);
5.刪除數(shù)據(jù):
$bulk = new MongoDBDriverBulkWrite;
$filter = [‘name’ => ‘john’];
$bulk->delete($filter, [‘limit’ => 1]);
$m->executeBulkWrite(‘testdb.collection’, $bulk);
以上就是PHP操作MongoDB的基本操作,用上述方法對MongoDB進(jìn)行CRUD操作即可,若能熟練運(yùn)用PHP操作MongoDB,很快能實(shí)現(xiàn)功能強(qiáng)大的應(yīng)用。
網(wǎng)友評論