天天看点

PHP7 操作MongoDB

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

1.使用$inc,实现数值叠加

$updateUser = [
                '$inc'=>[
                        "total_amount"=> 
                ]
        ];
        $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'       => ,
'limit'      => ,
'sort'      => [
                'create_time' => -,
],
'projection' => [
                '_id'    => ,
                'icon'   => ,
             ]
    ];

$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));

统计符合条件的数据总数
```php
$query  = ['name'=>'mike'];
$count  = $this->collection->count($query);
           

“`