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.


Parameters

config
IDbConfig

Database configuration object (optional)

Response

Database
Database

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

Example

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

// Initialize the application
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 (use default configuration)
const db = app.database();

// Get query command
const _ = db.command;

// Get position type
const Geo = db.Geo;

Collection Methods

createCollection

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

Create a collection.

Parameters

collName
string

Collection Name

Response

Promise
ICreateCollectionResult

Creation result

Example

Create a new collection
const result = await db.createCollection("new-collection");
console.log("Collection created successfully");

collection

db.collection(collName: string): CollectionReference

Retrieve collection reference for subsequent data operations.

Parameters

collName
string

Collection Name

Response

CollectionReference
CollectionReference

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

Example

// Get collection reference
const todosCollection = db.collection("todos");

// Query data within the collection
const result = await todosCollection.get();
console.log("query result:", result.data);

Document method

doc

doc(docId: string | number): DocumentReference

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

Parameters

docId
string | number

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

Response

DocumentReference
DocumentReference

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

Example

Query a single record by document ID.
const result = await db.collection("todos").doc("todo-id-123").get();

if (result.data && result.data.length > 0) {
console.log("query result:", result.data[0]);
} else {
console.log("document not found");
}

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

Parameters

data
object

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

Response

Promise
AddResult

Example

// Add a single record
const result = await db.collection("todos").add({
title: "Learn CloudBase"
content: "Complete the database operation tutorial"
completed: false,
priority: "high",
createdAt: new Date(),
tags: ["study", "technology"],
});

console.log("successful addition, document ID:", result.id);

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).

Parameters

No parameters

Response

Promise
GetResult

Example

// Get all documents in the collection (default max 100)
const result = await db.collection("todos").get();

console.log("query result:", result.data);
console.log("total:", result.total);

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

Parameters

condition
object

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

Response

Query
Query

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

Example

// Query all incomplete high-priority tasks
const result = await db
.collection("todos")
.where({
completed: false,
priority: "high",
})
.get();

console.log("query result:", result.data);

count

async count(): Promise<CountResult>

Statistics of the number of documents that match the condition.

Parameters

No parameters

Response

Promise
CountResult

Example

// Count the number of unfinished tasks
const result = await db.collection("todos").where({ completed: false }).count();

console.log("unfinished tasks:", result.total);

orderBy

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

Set the sorting method of query results.

Parameters

fieldPath
string

Sorting field path

direction
'asc' | 'desc'

Sorting order: asc ascending order, desc descending order

Response

Query
Query

Query object, can proceed with chained call

Example

// Sort by creation time in descending order
const result = await db.collection("todos").orderBy("createdAt", "desc").get();

limit

limit(max: number): Query

Set the maximum record count returned by the query.

Note
  • Default limit: 100 -supports up to 1000

Parameters

max
number

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

Response

Query
Query

Query object, can proceed with chained call

Example

// Only get the first 10 records
const result = await db.collection("todos").limit(10).get();

skip

skip(offset: number): Query

Set the query result offset for pagination queries.

Parameters

offset
number

Offset, must be a non-negative integer

Response

Query
Query

Query object, can proceed with chained call

Example

// Skip the first 20 records, get records 21-30
const result = await db.collection("todos").skip(20).limit(10).get();

field

field(projection: object): Query | DocumentReference

Specify the fields to return.

Parameters

projection
object

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

Response

Query | DocumentReference
Query | DocumentReference

Query object or document reference, can proceed with chained call

Example

Only return title and completed fields
const result = await db
.collection("todos")
.field({
title: true,
completed: true,
})
.get();

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.

Parameters

No parameters

Response

Aggregate
Aggregate

Aggregation object supporting chained calls of various aggregation stage methods

Example

// Count the number of tasks by priority
const result = await db
.collection("todos")
.aggregate()
.group({
_id: "$priority",
count: {
$sum: 1,
},
})
.end();

console.log("count by priority:", result.data);
// Output: [{ _id: 'high', count: 5 }, { _id: 'normal', count: 10 }, ...]

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

Parameters

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

Response

Query
Query

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

Example

const _ = db.command;

// Query nearby users (sorted by distance)
const result = await db
.collection("users")
.where({
location: _.geoNear({
geometry: new db.Geo.Point(116.404, 39.915), // Tiananmen coordinate
maxDistance: 1000, // Maximum distance 1000 meters
minDistance: 0, // minimum distance 0 meters
}),
})
.get();

console.log("nearby users:", result.data);

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

Parameters

data
object

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

Response

Promise
UpdateResult

Example

// Update the specified document
const result = await db.collection("todos").doc("todo-id-123").update({
title: "Learn CloudBase Database"
completed: true,
updatedAt: new Date(),
completedBy: "user123",
});

console.log("update succeeded, number of records impacted:", result.updated);

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

Parameters

data
object

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

Response

Promise
SetResult

Example

// Update the document, if it does not exist create
const result = await db.collection("todos").doc("todo-id-123").set({
title: "New Task",
completed: false,
priority: "high",
createdAt: new Date(),
});

if (result.upsertedId) {
console.log("create new document, ID:", result.upsertedId);
} else {
console.log(
"update existing document, number of records impacted:",
result.updated
);
}

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.

Parameters

No parameters

Response

Promise
RemoveResult

Example

// Delete specified document
const result = await db.collection("todos").doc("todo-id-123").remove();

console.log(
"Deleted successfully, number of records impacted:",
result.deleted
);

Operator

Query operator

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

Parameters

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

Response

No parameters

Example

const _ = db.command;

Equal to
db.collection("users").where({ age: _.eq(18) });

Not equal to
db.collection("users").where({ status: _.neq("deleted") });

Greater than, greater than or equal to
db.collection("users").where({ age: _.gt(18) });
db.collection("users").where({ age: _.gte(18) });

Less than, less than or equal to
db.collection("users").where({ age: _.lt(60) });
db.collection("users").where({ age: _.lte(60) });

// In the array
db.collection("users").where({ role: _.in(["admin", "editor"]) });

Not in the array
db.collection("users").where({ status: _.nin(["banned", "deleted"]) });

Update operator

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

Parameters

Field Operators
object
Array Operators
object

Response

No parameters

Example

const _ = db.command;

//Set field value
db.collection("users")
.doc("user-id")
.update({
profile: _.set({ name: "Zhang San", age: 25 }),
});

// Delete field
db.collection("users").doc("user-id").update({
tempData: _.remove(),
});

// Numeric value increment
db.collection("articles")
.doc("article-id")
.update({
viewCount: _.inc(1),
likeCount: _.inc(5),
});

// Numeric value multiplication
db.collection("products")
.doc("product-id")
.update({
price: _.mul(0.9), // 10% off
});

// Get the minimum/maximum value
db.collection("users")
.doc("user-id")
.update({
minScore: _.min(60),
maxScore: _.max(100),
});

// Rename field
db.collection("users")
.doc("user-id")
.update({
oldField: _.rename("newField"),
});

// Bitwise Operation
db.collection("users")
.doc("user-id")
.update({
flags: _.bit({ and: 5 }), // Bitwise AND operation
});

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.

Parameters

No parameters

Response

Promise
Transaction

Transaction object, perform document operations in a transaction

Example

// Start a transaction.
const transaction = await db.startTransaction();

try {
// Operate document in transaction
const doc = transaction.collection("accounts").doc("account-1");
const accountData = await doc.get();

if (accountData.data && accountData.data.balance >= 100) {
// Deducting funds
await doc.update({
balance: accountData.data.balance - 100,
});

// Add balance to another account
await transaction
.collection("accounts")
.doc("account-2")
.update({
balance: db.command.inc(100),
});

// Commit transactions.
await transaction.commit();
console.log("Fund transfer successful");
} else {
// Roll back transaction
await transaction.rollback("INSUFFICIENT_BALANCE");
}
} catch (error) {
// Roll back when an error occurs
await transaction.rollback(error);
console.error("Transaction failure:", error);
}

runTransaction

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

Execute transaction operations with automatic processing of submission and rollback.

Parameters

callback
(transaction) => Promise<void>

Transactional callback function, perform transaction operations in the function

times
number

Retry count for transaction conflicts, defaults to 3

Response

Promise
void

Function return value of the transactional callback function

Example

Use runTransaction to automatically manage transactions
const result = await db.runTransaction(async (transaction) => {
// Obtain account 1
const account1 = await transaction
.collection("accounts")
.doc("account-1")
.get();

Obtains account 2
const account2 = await transaction
.collection("accounts")
.doc("account-2")
.get();

if (account1.data.balance < 100) {
// Roll back via rollback and return custom error
await transaction.rollback({ message: "INSUFFICIENT_BALANCE" });
return;
}

// Deducting funds
await transaction
.collection("accounts")
.doc("account-1")
.update({
balance: account1.data.balance - 100,
});

// Adding funds
await transaction
.collection("accounts")
.doc("account-2")
.update({
balance: account2.data.balance + 100,
});

return { success: true, message: "Fund transfer successful" };
});

console.log(result);

Real-time listening

watch

watch(options: WatchOptions): DBRealtimeListener

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

Parameters

options
WatchOptions

Response

DBRealtimeListener
object

Listener object

Example

Listen to changes in a single document
const listener = db
.collection("todos")
.doc("todo-id-123")
.watch({
onChange: (snapshot) => {
console.log("document changes:", snapshot);
console.log("document data:", snapshot.docs);
console.log("change details:", snapshot.docChanges);
},
onError: (error) => {
console.error("Listen error:", error);
},
});

// Close listener
// listener.close();

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.

Parameters

params
IRunCommandsReq

Response

Promise
IRunCommandsResult

Example

// Execute the find command
const result = await db.runCommands({
commands: [
{
find: "users",
filter: { age: { $gte: 18 } },
projection: { name: 1, email: 1 },
sort: { age: -1 },
limit: 10,
},
],
});

console.log("query result:", result.list);
// result.list[0] contains the queried document

Other functions

serverDate

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

Get server time.

Parameters

options
object

Response

ServerDate
ServerDate

Server time object

Example

// Use server time
await db.collection("todos").add({
title: "New Task"
createdAt: db.serverDate(), // Current server time
});

// Use server time with offset
await db.collection("todos").add({
title: "Delayed Task"
scheduledAt: db.serverDate({
offset: 60 * 60 * 1000, // 1 hour later
}),
});

RegExp

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

Create a regular expression object for fuzzy query.

Parameters

options
object

Response

RegExp
RegExp

regular expression object

Example

// Fuzzy query: heading contains "CloudBase"
const result = await db
.collection("todos")
.where({
title: db.RegExp({
regexp: "CloudBase",
options: "i", // case-insensitive
}),
})
.get();

console.log("query result:", result.data);

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