1. 程式人生 > >PHP7 操作MongoDB

PHP7 操作MongoDB

//先定義
$this->collection = (new \MongoDB\Client($host))->selectDatabase('my_db')->selectCollection('my_collection');

1.使用$inc,實現數值疊加

        $updateUser = [
                '$inc'=>[
                        "total_amount"=> 10
                ]
        ];
        $userFilter = [
            '_id'
=> '123', ]; $this->collection->updateOne($userFilter, $updateUser);
  • 讓指定collection中“_id”為“123的資料,“total_amount”欄位加上10,若操作前前”total_amount”的值為8,則操作後值為18.

2.將cursor轉換成array

$res = $this->collection->find()->toArray();
$res = json_encode($res);

3.option中引數的順序問題

//skip、limit須在project之前否則報錯
$query = []; $option = [ 'skip' => 0, 'limit' => 5, 'sort' => [ 'create_time' => -1, ], 'projection' => [ '_id' => 1, 'icon' => 1, ] ]; $res = $this->collection->find($query,$option)->toArray();

4.empty()檢驗MongoDB 物件

$query  = ['name'=>'mike'];
$cursor = $this->collection->findOne($query);
//若不存在name 為mike的資料,則列印$cursor結果為true,反之為false
var_dump(empty($cursor));

5.統計符合條件的資料總數
```php
$query  = ['name'=>'mike'];
$count  = $this->collection->count($query);

“`