Skip to main content

database

Overview

Database API provides a complete set of document database operation features, supporting CRUD operations, complex queries, aggregation, location query, and transaction operations.

Note

Starting from v3.3, the related APIs use the HTTP API open capabilities.

Database API is divided into the following categories by feature purpose:

-Initialization: Get database instance


Basic usage example

Publishable Key can go to Cloud Development Platform/API Key Configuration to generate

import cloudbase from "@cloudbase/js-sdk";

// Initialize it.
const app = cloudbase.init({
env: "your-env-id", // Replace this value with your environment ID
region: "ap-shanghai", // Region, defaults to Shanghai
accessKey: "", // Fill in the generated Publishable Key
});

// Get database reference
const db = app.database();
// Get query command
const _ = db.command;
// Get position type
const Geo = db.Geo;

Initialization

database

app.database(config?: IDbConfig): Database

Get database instance for follow-up database operation. Visit Cloud Development Platform/document database for instance information retrieval.


参数

config
IDbConfig

Database configuration object (optional)

返回

Database
Database

Database instance object, callable attributes and methods such as collection(), command, Geo, and serverDate()

示例


Collection Methods

createCollection

async db.createCollection(collName: string): Promise<ICreateCollectionResult>

Create a collection.

参数

collName
string

Collection Name

返回

Promise
ICreateCollectionResult

Creation result

示例


collection

db.collection(collName: string): CollectionReference

Retrieve collection reference for subsequent data operations.

参数

collName
string

Collection Name

返回

CollectionReference
CollectionReference

Collection reference object, can use chained call doc(), where(), add(), aggregate() methods

示例


Document method

doc

doc(docId: string | number): DocumentReference

Get a document reference by document ID for follow-up queries, updates, or deletion.

参数

docId
string | number

Unique identifier of the document, supports string or number data type

返回

DocumentReference
DocumentReference

Document reference object, can use chained call get(), update(), set(), remove(), field() methods

示例


Add data

add

async add(data: object): Promise<AddResult>

Add a new record to the collection.

-Add a single data record to the specified collection -Support automatic generation of document IDs, or specify a document ID

  • Support the geographic location data type

参数

data
object

The data object to be added, supporting nested objects, arrays, geographic locations and other data types

返回

Promise
AddResult

示例


Query data

get

async get(): Promise<GetResult>

Get query results, return the document list that matches the condition.

Note

-Return up to 100 records by default

  • Support returning a maximum of 1000 records (set via limit).

参数

无参数

返回

Promise
GetResult

示例


where

where(condition: object): Query

Set query conditions, support various operators to perform complex condition filtering.

Note

-Query condition must be object type -The value of the condition object cannot all be undefined

参数

condition
object

The query condition object, supporting equivalent matching, operator matching, nested field matching and other types

返回

Query
Query

Query object, can use chained call orderBy(), limit(), skip(), field(), get(), count(), update(), remove() methods

示例


count

async count(): Promise<CountResult>

Statistics of the number of documents that match the condition.

参数

无参数

返回

Promise
CountResult

示例


orderBy

orderBy(fieldPath: string, direction: 'asc' | 'desc'): Query

Set the sorting method of query results.

参数

fieldPath
string

Sorting field path

direction
'asc' | 'desc'

Sorting order: asc ascending order, desc descending order

返回

Query
Query

Query object, can proceed with chained call

示例


limit

limit(max: number): Query

Set the maximum record count returned by the query.

Note
  • Default limit: 100 -supports up to 1000

参数

max
number

Maximum return record count, must be a positive integer, maximum value of 1000

返回

Query
Query

Query object, can proceed with chained call

示例


skip

skip(offset: number): Query

Set the query result offset for pagination queries.

参数

offset
number

Offset, must be a non-negative integer

返回

Query
Query

Query object, can proceed with chained call

示例


field

field(projection: object): Query | DocumentReference

Specify the fields to return.

参数

projection
object

Field projection object. true means return this field, false means do not return

返回

Query | DocumentReference
Query | DocumentReference

Query object or document reference, can proceed with chained call

示例


aggregate

aggregate(): Aggregate

Get the aggregation object for execution of aggregate queries, supporting aggregation stages such as group, match, sort, and project.

Note

Refer to the aggregate query for aggregation grammar.

参数

无参数

返回

Aggregate
Aggregate

Aggregation object supporting chained calls of various aggregation stage methods

示例


Geolocation query

Support spatial querying for geolocation fields, including nearby queries, region queries, and intersect queries.

Note

When querying a geolocation field, create a geo-indexing, otherwise the query will fail

参数

geoNear
GeoNearOptions

Nearby queries, return results sorted by distance

geoWithin
GeoWithinOptions

Region query, return results within the specified region

geoIntersects
GeoIntersectsOptions

Intersect query, return results that intersect with the specified geometric shape

返回

Query
Query

Query object, can use chained call get() method to obtain result

示例


Update data

update

async update(data: object): Promise<UpdateResult>

Update document data. Single-entry update and batch update are supported.

-Update a single record via doc().update()

  • Update multiple records in batch via where().update() -Supports the use of update operators to perform complex updates -Cannot update the _id field

参数

data
object

The data object to be updated, supporting updates to common fields and operators

返回

Promise
UpdateResult

示例


set

async set(data: object): Promise<SetResult>

Set document data, if the document does not exist create a new document.

-Unlike update(), set() replaces document content -Suitable for scenarios where refresh or create is required. -Cannot contain update operators -Cannot update the _id field

参数

data
object

The data object to be set will replace all existing document content and cannot contain update operators

返回

Promise
SetResult

示例


Delete data

remove

async remove(): Promise<RemoveResult>

Delete document. Support single deletion and delete in batches.

-Delete a single record with doc().remove()

  • Delete multiple records in batch via where().remove()
Note

When deleting in batches, the offset, limit, projection, and orderBy parameters will be ignored.

参数

无参数

返回

Promise
RemoveResult

示例


Operator

Query operator

Get the query operator via db.command to build complex query conditions.

参数

Comparison Operators
object
Logical Operators
object
Field Operators
object
Array Operators
object
Geospatial Operators
object

返回

无参数

示例


Update operator

Get the update operator via db.command for execution of complex update operations.

参数

Field Operators
object
Array Operators
object

返回

无参数

示例


Transaction Operations

Support atomic operations on multiple documents to underwrite data consistency.

Note

-Support only server-side use, not supported on the client.

startTransaction

async db.startTransaction(): Promise<Transaction>

Start a new transaction.

参数

无参数

返回

Promise
Transaction

Transaction object, perform document operations in a transaction

示例


runTransaction

async db.runTransaction(callback: (transaction) => Promise<any>, times?: number): Promise<void>

Execute transaction operations with automatic processing of submission and rollback.

参数

callback
(transaction) => Promise<void>

Transactional callback function, perform transaction operations in the function

times
number

Retry count for transaction conflicts, defaults to 3

返回

Promise
void

Function return value of the transactional callback function

示例


Real-time listening

watch

watch(options: WatchOptions): DBRealtimeListener

Listen to real-time changes in documents or query results.

参数

options
WatchOptions

返回

DBRealtimeListener
object

Listener object

示例


Advanced operation

runCommands

async db.runCommands(params: IRunCommandsReq): Promise<IRunCommandsResult>

Execute MongoDB native commands, support batch operations for multiple commands and transaction operations.

Note

-Only the administrator can call the API -During execution in a transaction, any command failure would cause the entire transaction rollback.

参数

params
IRunCommandsReq

返回

Promise
IRunCommandsResult

示例


Other functions

serverDate

db.serverDate(options?: { offset?: number }): ServerDate

Get server time.

参数

options
object

返回

ServerDate
ServerDate

Server time object

示例


RegExp

db.RegExp({ regexp: string, options?: string }): RegExp

Create a regular expression object for fuzzy query.

参数

options
object

返回

RegExp
RegExp

regular expression object

示例


Aggregation Operator

Obtain aggregation operators through db.command.aggregate for expression calculation in the aggregation pipeline.

CategoryOperator
Arithmetic Operatorabs, add, ceil, divide, exp, floor, ln, log, log10, mod, multiply, pow, sqrt, subtract, trunc
Array OperatorarrayElemAt, arrayToObject, concatArrays, filter, in, indexOfArray, isArray, map, range, reduce, reverseArray, size, slice, zip
Boolean Operatorand, not, or
Comparison Operatorcmp, eq, gt, gte, lt, lte, neq
Conditional Operatorcond, ifNull, switch
Date OperatordateFromParts, dateFromString, dayOfMonth, dayOfWeek, dayOfYear, isoDayOfWeek, isoWeek, isoWeekYear, millisecond, minute, month, second, hour, week, year
String Operatorconcat, dateToString, indexOfBytes, indexOfCP, split, strLenBytes, strLenCP, strcasecmp, substr, substrBytes, substrCP, toLower, toUpper
Set OperatorallElementsTrue, anyElementTrue, setDifference, setEquals, setIntersection, setIsSubset, setUnion
Object OperatormergeObjects, objectToArray
Grouping OperatoraddToSet, avg, first, last, max, min, push, stdDevPop, stdDevSamp, sum
Otherliteral, let, meta

-Detailed documentation for aggregate query