PHP7 MongoDB 使用方法


原文鏈接: http://www.zhaokeli.com/article/8574.html

MongoDb原生操作

Mongodb連接

PHP7 連接 MongoDB 語法如下:

復制代碼
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

插入數據

將 name 為"自學教程" 的數據插入到 test 數據庫的 runoob 集合中。

復制代碼
$bulk = new MongoDB\Driver\BulkWrite;
$document = ['_id' => new MongoDB\BSON\ObjectID, 'name' => '菜鳥教程'];   $_id= $bulk->insert($document);   var_dump($_id);   $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");   $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000); $result = $manager->executeBulkWrite('test.runoob', $bulk, $writeConcern);

讀取數據

復制代碼
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");     // 插入數據 $bulk = new MongoDB\Driver\BulkWrite; $bulk->insert(['x' => 1, 'name'=>'baidu', 'url' => 'http://www.baidu.com']); $bulk->insert(['x' => 2, 'name'=>'Google', 'url' => 'http://www.google.com']); $bulk->insert(['x' => 3, 'name'=>'taobao', 'url' => 'http://www.taobao.com']); $manager->executeBulkWrite('test.sites', $bulk);   $filter = ['x' => ['$gt' => 1]]; $options = [     'projection' => ['_id' => 0],     'sort' => ['x' => -1], ];   // 查詢數據 $query = new MongoDB\Driver\Query($filter, $options); $cursor = $manager->executeQuery('test.sites', $query);   foreach ($cursor as $document) {     print_r($document); }

更新數據

復制代碼
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
    ['x' => 2],     ['$set' => ['name' => '菜鳥工具', 'url' => 'tool.runoob.com']],     ['multi' => false, 'upsert' => false] );   $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");   $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000); $result = $manager->executeBulkWrite('test.sites', $bulk, $writeConcern);

刪除數據

復制代碼
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['x' => 1], ['limit' => 1]);   // limit 為 1 時,刪除第一條匹配數據 $bulk->delete(['x' => 2], ['limit' => 0]);   // limit 為 0 時,刪除所有匹配數據   $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");   $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000); $result = $manager->executeBulkWrite('test.sites', $bulk, $writeConcern);

MongoDB官方操作庫

看完上面的CURD操作是不是感覺有點懵逼,操作方式跟想像中的完全不一樣,可能官方也想到啦這一塊,於是又封裝啦一個操作庫讓大家使用。文檔地址如下

https://docs.mongodb.com/php-library/current/tutorial/crud/

安裝

復制代碼
composer require mongodb/mongodb

添加數據

插入單條數據

在數據庫test中的users集合中插入數據,如果數據庫或集合不存在則會自動創建

復制代碼
$collection      = (new MongoDB\Client)->test->users;
$insertOneResult = $collection->insertOne([
    'username' => 'admin',     'email'    => 'admin@example.com',     'name'     => 'Admin User', ]); printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount()); var_dump($insertOneResult->getInsertedId());

輸出結果

1905281559025619827923.png

數據庫中數據

1905281559025567787873.png

可以看出返回$oid為數據庫自動分配的唯一標識,如果我們插入的時候傳入id值的話,mongodb會判斷這個id是否存在,如果存在就會報錯,如果不存在則直接返回傳入的id值

復制代碼
$collection      = (new MongoDB\Client)->test->users;
$insertOneResult = $collection->insertOne(['_id' => 1, 'name' => 'Alice']); printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount()); var_dump($insertOneResult->getInsertedId());

執行結果

1905281559025985889303.png

插入多條數據

復制代碼
$collection = (new MongoDB\Client)->test->users;
$insertManyResult = $collection->insertMany([
    [
        'username' => 'admin',         'email' => 'admin@example.com',         'name' => 'Admin User',     ],     [         'username' => 'test',         'email' => 'test@example.com',         'name' => 'Test User',     ],]); printf("Inserted %d document(s)\n", $insertManyResult->getInsertedCount()); var_dump($insertManyResult->getInsertedIds());

1905281559026233129220.png

查詢數據

如果要使用id查詢,則需要使用下面的ObjectId類來封裝下傳進去

使用自增id查詢

復制代碼
$collection = (new MongoDB\Client)->test->users;
$id         = new \MongoDB\BSON\ObjectId('5cecd708ab4e4536fc0076e2'); $document   = $collection->findOne(['_id' => $id]); var_dump($document);

其它條件查詢

使用其它條件數據則直接傳進去就可以 

復制代碼
$collection = (new MongoDB\Client)->test->users;
$document   = $collection->findOne(['username' => 'admin']); var_dump($document);

1905281559027257136568.png

使用limit,sort,skip查詢

默認情況下是返回所有的字段數據,也可以指定字段返回,limit是返回的行數,sort是使用name字段-1為降序,1為升序,skip為跳過前多少條數據如下

復制代碼

$collection = (new MongoDB\Client)->test->users;
$cursor     = $collection->find(
    [
        'username' => 'admin',     ],     [         'projection' => [             'email' => 1,         ],         'limit'      => 4,         'sort'       => ['name' => -1],         'skip'       =>1,     ]); foreach ($cursor as $restaurant) {     var_dump($restaurant); }

正則條件查詢

復制代碼

$collection = (new MongoDB\Client)->test->users;
$cursor     = $collection->find(
    [
        'username' => new MongoDB\BSON\Regex('^ad', 'i'),     ],     [         'projection' => [             'email' => 1,         ],         'limit'      => 1,         'sort'       => ['pop' => -1],     ]); foreach ($cursor as $restaurant) {     var_dump($restaurant); }

另外一種正則式的寫法

復制代碼

$collection = (new MongoDB\Client)->test->users;
$cursor     = $collection->find(
    [
        'username' => ['$regex' => '^ad', '$options' => 'i'],     ],     [         'projection' => [             'email' => 1,         ],         'limit'      => 1,         'sort'       => ['pop' => -1],     ]); foreach ($cursor as $restaurant) {     var_dump($restaurant); }

查詢多個數據

復制代碼

$collection = (new MongoDB\Client)->test->users;
$cursor     = $collection->find(['username' => 'admin']); foreach ($cursor as $document) {     echo $document['_id'], "\n"; }

1905281559027339129636.png

更新數據

更新單條數據

復制代碼

$collection   = (new MongoDB\Client)->test->users;
$updateResult = $collection->updateOne(
    ['username' => 'admin'],     ['$set' => ['name' => 'new nickname']] ); printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

1905281559029206114764.png

更新多條數據

復制代碼

$collection   = (new MongoDB\Client)->test->users;
$updateResult = $collection->updateMany(
    ['username' => 'admin'],     ['$set' => ['name' => 'new nickname']] ); printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

1905281559029272301679.png

替換文檔

替換文檔其它跟更新數據類似,但是這個操作不會修改id,如下

復制代碼

$collection   = (new MongoDB\Client)->test->users;
$updateResult = $collection->replaceOne(
    ['username' => 'admin'],     ['username' => 'admin2', 'name' => 'new nickname'] ); printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

Upsert操作

這個名字應該是個縮寫,更新或替換操作時如果有匹配的數據則直接操作,如果沒有匹配的數據則插入一條新數據,意思是如果更新或替換操作的第三個參數如果傳 'upsert'=>True 的話就可以開啟這個功能

復制代碼

$collection   = (new MongoDB\Client)->test->users;
$updateResult = $collection->updateOne(
    ['username' => 'admin3'],     ['$set' => ['username' => 'admin2', 'name' => 'new nickname']],     ['upsert' => true] ); printf("Matched %d document(s)\n", $updateResult->getMatchedCount()); printf("Modified %d document(s)\n", $updateResult->getModifiedCount()); printf("Upserted %d document(s)\n", $updateResult->getUpsertedCount()); $upsertedDocument = $collection->findOne([     '_id' => $updateResult->getUpsertedId(), ]); var_dump($upsertedDocument);

如果有匹配的情況下最后輸出為NULl

1905281559030215132171.png

沒有匹配的情況下最后輸出插入的數據

1905281559030085203984.png

刪除數據

復制代碼

$collection   = (new MongoDB\Client)->test->users;
$deleteResult = $collection->deleteOne(['username' => 'admin3']); printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount()); $deleteResult = $collection->deleteMany(['username' => 'admin2']); printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());

1905281559030350141184.png


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM