1. 程式人生 > >php MongoDB 操作示例

php MongoDB 操作示例

object stat use ble b- 排序 獲取 itl eat

  • 查詢

    $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() 獲取查詢結果匹配數
  • 聚簇
  • php MongoDB 操作示例