php 7のmongodbの基本的な使い方

4100 ワード

ヒント:PHPのmongodb拡張は、5.6から元のmongo拡張を廃棄し、php 7のpeclダウンロードアドレス:https://pecl.php.net/package/mongodbまたはmongodbの公式開発を選択します.https://github.com/mongodb/mongo-php-library,git上のこのサポートは以前のmongo書き方,pecl上のmongodbは以前の書き方をサポートしていない.
PHP 7の新しいAPIでまとめてみます.
一:CURD
1:リンク


rootユーザー;123:パスワード;パスワードがない場合は書かない
2:クエリー
['$gt'=>0]]; //     user_id  0
$options = [
   'projection' => ['_id' => 0], //   _id  
   'sort' => ['user_id'=>-1] //  user_id     1   ,-1   
];
$query = new MongoDB\Driver\Query($filter, $options); //    
$list = $manager->executeQuery('location.box',$query); //      location     box  


foreach ($list as $document) {
    print_r($document); 
}

クエリーの詳細条件の使用方法、第2節mongodb基本コマンドを参照して、クエリー
3:追加
 flase]);//           flase,    
$bulk->insert(['user_id' => 2, 'real_name'=>'  ',]);
$bulk->insert(['user_id' => 3, 'real_name'=>'   ',]);
$manager->executeBulkWrite('location.box', $bulk); //     location     box  

4:変更
 flase]);//           flase,    
$bulk->update(
	['user_id' => 2],
	['$set'=>['real_name'=>'   ']
]); 
//$set   mysql  set,   mysql        ,
//1:            ;
//2:mongodb         ,     ,   insert


//           ,      upsert
//db.collectionName.update(query, obj, upsert, multi);

$bulk->update(
	['user_id' => 5],
	[
		'$set'=>['fff'=>'   ']
	],
	['multi' => true, 'upsert' => false] 
	//multi true,          ,   true,    false,            
	//upsert  treu:        
);
$manager->executeBulkWrite('location.box', $bulk); //     location     box  

ordered設定1:デフォルトはtureで、挿入更新データを順番に実行し、エラーが発生した場合、実行を停止した後、mongo公式はシリアルと呼ばれます.2:falseの場合、mongoは同時に更新データを挿入し、中間にエラーが発生し、後続の操作に影響を及ぼさず、mongoはパラレルと呼ばれます.
5:削除
 flase]);//           flase,    
$bulk->delete(['user_id'=>5]);//  user_id 5   
$manager->executeBulkWrite('location.box', $bulk); //     location     box  

deleteはlimitで異なる削除方法を設定することもできます
$bulk->delete(['user_id' => 1], ['limit' => 1]);   // limit   1  ,         
$bulk->delete(['user_id' => 2], ['limit' => 0]);   // limit   0  ,        ,      

6:捕获异常

MongoDB\Driver\Exception\AuthenticationException
MongoDB\Driver\Exception\BulkWriteException
MongoDB\Driver\Exception\ConnectionException
MongoDB\Driver\Exception\ConnectionTimeoutException
MongoDB\Driver\Exception\Exception //             
MongoDB\Driver\Exception\ExecutionTimeoutException
MongoDB\Driver\Exception\InvalidArgumentException
MongoDB\Driver\Exception\LogicException
MongoDB\Driver\Exception\RuntimeException
MongoDB\Driver\Exception\SSLConnectionException
MongoDB\Driver\Exception\UnexpectedValueException
MongoDB\Driver\Exception\WriteException

説明:http://php.net/manual/zh/class.mongodb-driver-exception-authenticationexception.php
クリックしてすべてを表示