• 查询

    $filter = [
                '_id' => new MongoDB\BSON\ObjectId("$id"),
                'creater_id' => $user['user_id'],
                'delete_flag' => 'N',
            ];  // 查询条件
    
            $options = [
                'projection' => ['_id' => 1, 'id' => 1, 'title' => 1, 'status' => 1, 'delete_flag' => 1],
                                'limit' => $page_size,                                                       // limit
                                'skip' => (int)(($page_index - 1) * $page_size),               // 跳过
                                'sort' => ['create_time' => -1]                                            // 排序
            ];  // 操作项
    
            $doc = $this->mongo_db->findOne('table', $filter, $options);
            return !empty($doc) ? $doc->getArrayCopy() : [];
            // getArrayCopy() 将查询结果转为数组
  • 更新

    $filter = [
            '_id' => new MongoDB\BSON\ObjectId("$id")  // 匹配条件
        ];
    
        $options = [
            '$set' => ['delete_flag' => 'Y']   // 设置要更新的字段值
        ];
    
        $doc = $this->mongo_db->updateOne('table', $filter, $options);
        $modified_count = $doc->getModifiedCount();
        if ($modified_count == 1)
        {
            return true;
        }
    
                // getModifiedCount() 获取被影响行数
                // getMatchedCount() 获取查询结果匹配数
  • 聚簇
  • 求和

$pipeline = [
[
'$match' => [
'creater_id' => $user_id // 筛选条件
],
],
[
'$group' => [
'_id' => '$user_id', // group by 字段
'active_degree' => [
'$sum' => '$column_name' // 求和字段
]
]
]
];

    $options = [];
    $obj = $this->mongo_db->aggregate('collection', $pipeline, $options)->toarray();
            $data = $obj[0]->getArrayCopy()['column_name'];