openapi: 3.0.0

info:
  title: NoSQL RESTful API
  version: 1.0.0
  description: >-
    ### Overview

    RESTful HTTP API for the Document Database (NoSQL), providing collection management, document CRUD, aggregation queries, transaction operations, and database command execution.


    ### Request Domain

    ```

    https://{envId}.api.tcloudbasegateway.com/v1/database/instances/{instance}/databases/{database}/

    ```


    URL path parameters:

    - `envId`: Environment ID

    - `instance`: Instance ID, cannot be empty. Use `(default)` for the default instance

    - `database`: Database name, cannot be empty. Use `(default)` for the default database


    Examples:

    - Access the default instance's default database: `/v1/database/instances/(default)/databases/(default)/`

    - Access instance `test_instance`'s default database: `/v1/database/instances/test_instance/databases/(default)/`

    - Access instance `test_instance`'s database `mydb`: `/v1/database/instances/test_instance/databases/mydb/`


    ### EJSON Format

    Request bodies support both Relaxed EJSON and Strict EJSON formats. Response bodies are always in Strict EJSON format.


    EJSON (Extended JSON) is MongoDB's extended JSON format that supports data types not available in standard JSON:

    - `ObjectId`: `{"$oid": "507f1f77bcf86cd799439011"}`

    - `Date`: `{"$date": {"$numberLong": "1736929200000"}}`

    - `Int`: `{"$numberInt": "12345"}`

    - `Long`: `{"$numberLong": "9223372036854775807"}`

    - `Decimal128`: `{"$numberDecimal": "123.456"}`

    - `Binary`: `{"$binary": {"base64": "...", "subType": "00"}}`

    - `RegExp`: `{"$regex": "pattern", "$options": "i"}`


    ### Getting Started

    All API calls require an AccessToken in the format `Authorization: Bearer <token>`. For token acquisition, refer to: https://docs.cloudbase.net/http-api/basic/access-token


    ### Error Codes and HTTP Status Codes

    <table>
      <thead>
        <tr>
          <td>Error Code</td>
          <td>HTTP Status</td>
          <td>Description</td>
        </tr>
      </thead>
      <tbody>
        <tr><td>INVALID_PARAM</td><td>400</td><td>Invalid or missing parameter</td></tr>
        <tr><td>DATABASE_PERMISSION_DENIED</td><td>401</td><td>Database permission denied</td></tr>
        <tr><td>DATABASE_INVALID_OPERRATOR</td><td>403</td><td>Unsupported operation</td></tr>
        <tr><td>DATABASE_COLLECTION_NOT_EXIST</td><td>404</td><td>Collection does not exist</td></tr>
        <tr><td>DOCUMENT_NOT_FOUND</td><td>404</td><td>Document not found (single document operations only)</td></tr>
        <tr><td>DATABASE_COLLECTION_ALREADY_EXIST</td><td>409</td><td>Collection already exists</td></tr>
        <tr><td>DATABASE_DUPLICATE_WRITE</td><td>409</td><td>Unique index conflict</td></tr>
        <tr><td>EXCEED_REQUEST_LIMIT</td><td>422</td><td>Request quota exceeded</td></tr>
        <tr><td>EXCEED_CONCURRENT_REQUEST_LIMIT</td><td>422</td><td>Concurrent connection limit exceeded</td></tr>
        <tr><td>DATABASE_REQUEST_FAILED</td><td>500</td><td>Database request failed</td></tr>
        <tr><td>SYS_ERR</td><td>500</td><td>Internal system error</td></tr>
        <tr><td>DATABASE_TRANSACTION_CONFLICT</td><td>503</td><td>Transaction conflict</td></tr>
        <tr><td>DATABASE_TRANSACTION_FAIL</td><td>503</td><td>Transaction execution failed</td></tr>
        <tr><td>DATABASE_TIMEOUT</td><td>504</td><td>Database operation timeout</td></tr>
      </tbody>
    </table>

tags:
  - name: 集合操作
    description: Collection creation and management
  - name: 文档操作
    description: Document CRUD operations, supporting both batch and single document operations
  - name: 聚合查询
    description: Complex data analysis using MongoDB aggregation pipelines
  - name: 事务操作
    description: Transaction creation, commit, and rollback
  - name: 数据库命令
    description: Execute native MongoDB database commands (batch)

servers:
  - url: https://{envId}.api.tcloudbasegateway.com/v1/database/instances/{instance}/databases/{database}
    description: CloudBase Document Database API
    variables:
      envId:
        default: "your-envId"
        description: Environment ID
      instance:
        default: "(default)"
        description: Instance ID, use (default) for the default instance
      database:
        default: "(default)"
        description: Database name, use (default) for the default database

paths:
  /collections:
    post:
      tags:
        - 集合操作
      operationId: createCollection
      summary: Create Collection
      description: >-
        Create a new collection (table). Only administrators can create collections. Collection names must comply with MongoDB naming conventions.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - collectionName
              properties:
                collectionName:
                  type: string
                  description: Collection name
            example:
              collectionName: "users"
      responses:
        "201":
          description: Collection created successfully
        "400":
          description: Invalid request parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              example:
                code: "INVALID_PARAM"
                message: "Collection name is required"
                request_id: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
        "409":
          description: Collection already exists
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"

  /collections/{collectionName}/documents:
    post:
      tags:
        - 文档操作
      operationId: insertDocuments
      summary: Batch Insert Documents
      description: >-
        Insert one or more documents into the specified collection. Data format is an array of EJSON objects. Supports transaction operations.
      security:
        - bearerAuth: []
      parameters:
        - name: collectionName
          in: path
          description: Collection name
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - data
              properties:
                data:
                  type: array
                  items:
                    type: object
                  description: Array of document data (EJSON object format)
                transactionId:
                  type: string
                  description: Transaction ID (optional)
            example:
              data:
                - name: "Alice"
                  age:
                    $numberInt: "25"
                - name: "Bob"
                  age:
                    $numberInt: "30"
      responses:
        "201":
          description: Documents inserted successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  insertedIds:
                    type: array
                    items:
                      type: string
                    description: List of inserted document IDs
              example:
                insertedIds:
                  - "507f1f77bcf86cd799439011"
                  - "507f191e810c19729de860ea"
        "400":
          description: Invalid request parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"

    get:
      tags:
        - 文档操作
      operationId: queryDocuments
      summary: Query Document List
      description: >-
        Query documents in a collection. Supports complex query conditions (MongoDB query syntax), pagination, sorting, and field projection.

        When `count=true`, only returns the count of matching documents without the document list.
      security:
        - bearerAuth: []
      parameters:
        - name: collectionName
          in: path
          description: Collection name
          required: true
          schema:
            type: string
        - name: query
          in: query
          description: Query conditions (EJSON string), e.g. `{"age":{"$gte":18}}`
          required: false
          schema:
            type: string
            default: "{}"
        - name: offset
          in: query
          description: Offset for pagination
          required: false
          schema:
            type: integer
            default: 0
        - name: limit
          in: query
          description: Number of documents per page
          required: false
          schema:
            type: integer
            default: 20
        - name: order
          in: query
          description: Sort rules (JSON string), e.g. `[{"field":"age","direction":"desc"}]`
          required: false
          schema:
            type: string
        - name: projection
          in: query
          description: Field projection (JSON string), e.g. `{"name":1,"email":1}`
          required: false
          schema:
            type: string
        - name: count
          in: query
          description: Set to `true` to return only the document count
          required: false
          schema:
            type: boolean
        - name: transactionId
          in: query
          description: Transaction ID
          required: false
          schema:
            type: string
      responses:
        "200":
          description: Query successful
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    description: Document list result
                    properties:
                      offset:
                        type: integer
                        description: Current offset
                      limit:
                        type: integer
                        description: Documents per page
                      list:
                        type: array
                        items:
                          type: object
                        description: Document list (EJSON format)
                  - type: object
                    description: Count result (when count=true)
                    properties:
                      total:
                        type: integer
                        description: Total number of matching documents
              examples:
                list:
                  summary: Document list
                  value:
                    offset: 0
                    limit: 20
                    list:
                      - _id:
                          $oid: "507f1f77bcf86cd799439011"
                        name: "John Doe"
                        age:
                          $numberInt: "30"
                count:
                  summary: Count result (count=true)
                  value:
                    total: 42
        "400":
          description: Invalid request parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"

    patch:
      tags:
        - 文档操作
      operationId: updateDocuments
      summary: Batch Update Documents
      description: >-
        Update documents matching the query conditions. Supports MongoDB update operators (e.g. `$set`, `$inc`, `$push`, etc.).


        When `replaceMode` is `false` (default) and `data` does not contain update operators, it will be automatically wrapped with `$set`.


        Modifying `_openid` and `_id` fields is not allowed.
      security:
        - bearerAuth: []
      parameters:
        - name: collectionName
          in: path
          description: Collection name
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - query
                - data
              properties:
                query:
                  type: object
                  description: Query conditions (EJSON object)
                data:
                  type: object
                  description: Update data (EJSON object), supports update operators
                multi:
                  type: boolean
                  description: Whether to update multiple documents
                  default: false
                upsert:
                  type: boolean
                  description: Whether to create if not exists
                  default: false
                replaceMode:
                  type: boolean
                  description: Whether to replace the entire document (true = replace, false = merge update)
                  default: false
                transactionId:
                  type: string
                  description: Transaction ID
            example:
              query:
                _id:
                  $oid: "507f1f77bcf86cd799439011"
              data:
                $set:
                  age:
                    $numberInt: "31"
                  updated_at:
                    $date:
                      $numberLong: "1736929200000"
              multi: false
              upsert: false
              replaceMode: false
      responses:
        "200":
          description: Update successful
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/UpdateResult"
              example:
                updated: 1
                matched: 1
                upsert_id: ""
        "400":
          description: Invalid request parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"

  /collections/{collectionName}/documents/{docId}:
    get:
      tags:
        - 文档操作
      operationId: getDocumentById
      summary: Get Single Document
      description: >-
        Query a single document by its `_id`. Supports field projection and in-transaction queries. Returns 404 if the document does not exist.
      security:
        - bearerAuth: []
      parameters:
        - name: collectionName
          in: path
          description: Collection name
          required: true
          schema:
            type: string
        - name: docId
          in: path
          description: Document ID (supports both ObjectId strings and plain strings)
          required: true
          schema:
            type: string
        - name: projection
          in: query
          description: Field projection (JSON string), e.g. `{"name":1,"email":1}`
          required: false
          schema:
            type: string
        - name: transactionId
          in: query
          description: Transaction ID
          required: false
          schema:
            type: string
      responses:
        "200":
          description: Query successful
          content:
            application/json:
              schema:
                type: object
                description: Document content (EJSON format)
              example:
                _id:
                  $oid: "507f1f77bcf86cd799439011"
                name: "John Doe"
                age:
                  $numberInt: "30"
                email: "john@example.com"
        "404":
          description: Document not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              example:
                code: "DOCUMENT_NOT_FOUND"
                message: "Document not found"
                request_id: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

    patch:
      tags:
        - 文档操作
      operationId: updateDocumentById
      summary: Update Single Document
      description: >-
        Update a single document by its `_id`. Supports all update operators (`$set`, `$inc`, `$push`, etc.).

        Use `returnDoc=true` to return the updated document. Returns 404 if the document does not exist and `upsert=false`.
      security:
        - bearerAuth: []
      parameters:
        - name: collectionName
          in: path
          description: Collection name
          required: true
          schema:
            type: string
        - name: docId
          in: path
          description: Document ID (supports both ObjectId strings and plain strings)
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - data
              properties:
                data:
                  type: object
                  description: Update data (EJSON object), supports update operators
                replaceMode:
                  type: boolean
                  description: Whether to replace the entire document
                  default: false
                upsert:
                  type: boolean
                  description: Whether to create if not exists
                  default: false
                returnDoc:
                  type: boolean
                  description: Whether to return the updated document
                  default: false
                transactionId:
                  type: string
                  description: Transaction ID
            example:
              data:
                $set:
                  age:
                    $numberInt: "31"
              replaceMode: false
              returnDoc: true
      responses:
        "200":
          description: Update successful
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/UpdateResult"
                  - type: object
                    properties:
                      doc:
                        type: object
                        description: Updated document (only returned when returnDoc=true)
              examples:
                without_doc:
                  summary: Without document return
                  value:
                    updated: 1
                    matched: 1
                    upsert_id: ""
                with_doc:
                  summary: With updated document (returnDoc=true)
                  value:
                    updated: 1
                    matched: 1
                    upsert_id: ""
                    doc:
                      _id:
                        $oid: "507f1f77bcf86cd799439011"
                      name: "John"
                      age:
                        $numberInt: "31"
        "404":
          description: Document not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"

    delete:
      tags:
        - 文档操作
      operationId: deleteDocumentById
      summary: Delete Single Document
      description: >-
        Delete a single document by its `_id`. Uses the standard RESTful DELETE method. Returns 404 if the document does not exist.
      security:
        - bearerAuth: []
      parameters:
        - name: collectionName
          in: path
          description: Collection name
          required: true
          schema:
            type: string
        - name: docId
          in: path
          description: Document ID (supports both ObjectId strings and plain strings)
          required: true
          schema:
            type: string
        - name: transactionId
          in: query
          description: Transaction ID
          required: false
          schema:
            type: string
      responses:
        "200":
          description: Delete successful
          content:
            application/json:
              schema:
                type: object
                properties:
                  deleted:
                    type: integer
                    description: Number of deleted documents
              example:
                deleted: 1
        "404":
          description: Document not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              example:
                code: "DOCUMENT_NOT_FOUND"
                message: "Document not found"
                request_id: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

  /collections/{collectionName}/documents/remove:
    post:
      tags:
        - 文档操作
      operationId: removeDocuments
      summary: Batch Delete Documents
      description: >-
        Delete documents matching the query conditions. Uses POST method because complex query conditions need to be passed in the request body.

        The `query` cannot be an empty object (to prevent accidental deletion of all data). Non-admin users will have `_openid` conditions automatically injected.
      security:
        - bearerAuth: []
      parameters:
        - name: collectionName
          in: path
          description: Collection name
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - query
              properties:
                query:
                  type: object
                  description: Query conditions (EJSON object, cannot be empty)
                multi:
                  type: boolean
                  description: Whether to delete multiple documents
                  default: false
                transactionId:
                  type: string
                  description: Transaction ID
            example:
              query:
                _id:
                  $oid: "507f1f77bcf86cd799439011"
              multi: false
      responses:
        "200":
          description: Delete successful
          content:
            application/json:
              schema:
                type: object
                properties:
                  deleted:
                    type: integer
                    description: Number of deleted documents
              example:
                deleted: 1
        "400":
          description: Invalid request parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"

  /collections/{collectionName}/documents/aggregations:
    post:
      tags:
        - 聚合查询
      operationId: aggregate
      summary: Aggregation Query
      description: >-
        Perform complex data analysis using MongoDB native aggregation pipelines. Supported stages include: `$match`, `$group`, `$project`, `$sort`, `$limit`, `$skip`, `$unwind`, `$lookup` (admin only), `$addFields`, `$count`, `$sample`, `$bucket`, `$bucketAuto`, `$geoNear`, `$replaceRoot`, `$sortByCount`.


        Auto-limits: `$limit: 20` is automatically added when not specified. Under PRIVATE permissions, `$match: {_openid: "xxx"}` is automatically added.
      security:
        - bearerAuth: []
      parameters:
        - name: collectionName
          in: path
          description: Collection name
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - pipeline
              properties:
                pipeline:
                  type: array
                  items:
                    type: object
                  description: MongoDB native aggregation pipeline array, each element is an EJSON object containing a single aggregation stage
            examples:
              basic:
                summary: Basic aggregation query
                value:
                  pipeline:
                    - $match:
                        age:
                          $gte:
                            $numberInt: "18"
                    - $group:
                        _id: "$city"
                        count:
                          $sum:
                            $numberInt: "1"
                    - $sort:
                        count:
                          $numberInt: "-1"
                    - $limit: 10
              count:
                summary: $count aggregation
                value:
                  pipeline:
                    - $match:
                        status: "active"
                    - $count: "activeCount"
      responses:
        "200":
          description: Aggregation query successful
          content:
            application/json:
              schema:
                type: object
                properties:
                  list:
                    type: array
                    items:
                      type: object
                    description: Aggregation result list (EJSON format)
              examples:
                group:
                  summary: Grouping statistics result
                  value:
                    list:
                      - _id: "Beijing"
                        count: 150
                      - _id: "Shanghai"
                        count: 120
                count:
                  summary: Count result
                  value:
                    list:
                      - activeCount: 42
        "400":
          description: Invalid request parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"

  /transactions:
    post:
      tags:
        - 事务操作
      operationId: startTransaction
      summary: Start Transaction
      description: >-
        Start a new database transaction and return a transaction ID. Subsequent document operations can join this transaction via the `transactionId` parameter.
      security:
        - bearerAuth: []
      responses:
        "201":
          description: Transaction created successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  transactionId:
                    type: string
                    description: Transaction ID
              example:
                transactionId: "txn_abc123def456"

  /transactions/{transactionId}/commit:
    post:
      tags:
        - 事务操作
      operationId: commitTransaction
      summary: Commit Transaction
      description: >-
        Commit the specified transaction, making all operations within the transaction effective.
      security:
        - bearerAuth: []
      parameters:
        - name: transactionId
          in: path
          description: Transaction ID
          required: true
          schema:
            type: string
      responses:
        "204":
          description: Transaction committed successfully

  /transactions/{transactionId}/rollback:
    post:
      tags:
        - 事务操作
      operationId: rollbackTransaction
      summary: Rollback Transaction
      description: >-
        Rollback the specified transaction, undoing all operations within the transaction.
      security:
        - bearerAuth: []
      parameters:
        - name: transactionId
          in: path
          description: Transaction ID
          required: true
          schema:
            type: string
      responses:
        "204":
          description: Transaction rolled back successfully

  /commands:
    post:
      tags:
        - 数据库命令
      operationId: runCommands
      summary: Execute Database Commands
      description: >-
        Execute MongoDB native database commands in batch. All commands are executed sequentially and return a corresponding result array. Supports transaction execution.


        Only administrators and CloudBase OpenAPI can invoke this endpoint.


        Common commands include: `find`, `insert`, `update`, `delete`, `aggregate`, `createIndexes`, etc.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - commands
              properties:
                commands:
                  type: array
                  items:
                    type: object
                  description: Array of MongoDB native commands, each element is an EJSON object
                transactionId:
                  type: string
                  description: Transaction ID (execute all commands within the transaction)
            examples:
              find:
                summary: Find command
                value:
                  commands:
                    - find: "users"
                      filter:
                        age:
                          $gte:
                            $numberInt: "18"
                      limit:
                        $numberInt: "10"
              insert:
                summary: Insert command
                value:
                  commands:
                    - insert: "users"
                      documents:
                        - name: "Alice"
                          age:
                            $numberInt: "25"
                        - name: "Bob"
                          age:
                            $numberInt: "30"
              batch:
                summary: Batch commands (transaction)
                value:
                  commands:
                    - insert: "orders"
                      documents:
                        - userId: "user123"
                          amount:
                            $numberInt: "100"
                          status: "pending"
                    - update: "inventory"
                      updates:
                        - q:
                            productId: "prod456"
                          u:
                            $inc:
                              stock:
                                $numberInt: "-1"
                  transactionId: "txn_abc123"
      responses:
        "200":
          description: Commands executed successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  list:
                    type: array
                    items:
                      type: array
                      items:
                        type: object
                    description: 2D EJSON array, list[i] corresponds to the result of commands[i]
              example:
                list:
                  - - cursor:
                        firstBatch:
                          - _id:
                              $oid: "507f1f77bcf86cd799439011"
                            name: "John"
                            age:
                              $numberInt: "30"
                        id:
                          $numberLong: "0"
                        ns: "db.users"
                      ok:
                        $numberInt: "1"
        "400":
          description: Invalid request parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: Authenticate using AccessToken

  schemas:
    ErrorResponse:
      type: object
      properties:
        code:
          type: string
          description: Error code
          example: "INVALID_PARAM"
        message:
          type: string
          description: Error message
          example: "param.query can't be empty"
        request_id:
          type: string
          description: Unique request ID
          example: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

    UpdateResult:
      type: object
      properties:
        updated:
          type: integer
          description: Number of updated documents
        matched:
          type: integer
          description: Number of matched documents
        upsert_id:
          type: string
          description: ID of the upserted document (if any)
