php MongoDB 操作示例

  • 查询

    $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() 获取查询结果匹配数
  • 聚簇

猜你喜欢

转载自blog.51cto.com/13523022/2161767