database
Overview
Database API provides a complete set of document database operation features, supporting CRUD operations, complex queries, aggregation, location query, and transaction operations.
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
- Collection method: Get collection reference and create a collection
- Document method: Get document reference
- Newly added data: Add single or multiple data entries to the collection
- Query data: Support single query, conditional query, paging query, aggregate query and location query.
- Update data: Support single-entry update, batch update and update or create operations.
- Delete data: Support single deletion and delete in batches.
- Operators: Query operator and update operator.
- Transaction operations: Support activation, submission and rollback of transactions.
- Monitor in real time: Support real-time listening for document or query result changes.
- Advanced operations: Execute native MongoDB commands.
Basic usage example
- Initialization configuration
- Newly added data
- Query data
- Update Data
- Data deletion
- Batch operation
- Paging query
- Aggregation statistics
- Monitor in real time
- Error handling
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;
Add a new record to the collection.
async function addTodo() {
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);
}
// Add new record with specified document ID (use set)
async function addTodoWithId() {
const result = await db.collection("todos").doc("custom-id").set({
title: "Task with specified ID",
completed: false,
createdAt: new Date(),
});
console.log("successful addition");
}
// Query data within the collection
async function queryTodos() {
const _ = db.command;
// Conditional query: Incomplete high-priority task
const result = await db
.collection("todos")
.where({
completed: false,
priority: "high",
})
.orderBy("createdAt", "desc")
.limit(10)
.get();
console.log("query result:", result.data);
// Complex queries: Using operators
const complexResult = await db
.collection("todos")
.where({
// priority is high or medium
priority: _.in(["high", "medium"]),
Created in the last 7 days
createdAt: _.gte(new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)),
})
.field({
title: true,
priority: true,
createdAt: true,
})
.get();
console.log("complex query result:", complexResult.data);
}
// Update the specified document
async function updateTodo(todoId) {
const result = await db.collection("todos").doc(todoId).update({
completed: true,
updatedAt: new Date(),
});
console.log("update succeeded, number of records impacted:", result.updated);
}
// Update with operators
async function updateWithOperators(todoId) {
const _ = db.command;
const result = await db
.collection("todos")
.doc(todoId)
.update({
viewCount: _.inc(1)
viewCount: _.inc(1),
// Add a new tag (non-repetitive)
tags: _.addToSet("important"),
Update Time
updatedAt: new Date(),
});
console.log("Update successful");
}
// Delete specified document
async function deleteTodo(todoId) {
const result = await db.collection("todos").doc(todoId).remove();
console.log(
"Deleted successfully, number of records impacted:",
result.deleted
);
}
// Delete with conditions
async function deleteCompletedTodos() {
const result = await db
.collection("todos")
.where({
completed: true,
})
.remove();
console.log(
"Completed task deleted, number of records impacted:",
result.deleted
);
}
// Batch update: change ALL low-priority tasks to ordinary priority
async function batchUpdate() {
const result = await db
.collection("todos")
.where({
priority: "low",
})
.update({
priority: "normal",
updatedAt: new Date(),
});
console.log("batch update succeeded, number of records impacted:", result.updated);
}
Delete in batches: Delete tasks completed 30 days ago.
async function batchDelete() {
const _ = db.command;
const result = await db
.collection("todos")
.where({
completed: true,
createdAt: _.lt(new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)),
})
.remove();
console.log("Deleted in batches successfully, number of records impacted:", result.deleted);
}
// Paging query example
async function paginatedQuery(pageNum = 1, pageSize = 10) {
const result = await db
.collection("todos")
.where({
completed: false,
})
.orderBy("createdAt", "desc")
.skip((pageNum - 1) * pageSize)
.limit(pageSize)
.get();
console.log(`Page ${pageNum} data:`, result.data);
console.log("Current page count:", result.data.length);
return {
data: result.data,
pageNum,
pageSize,
};
}
// Get the total count used to calculate the total number of pages
async function getTotalCount() {
const result = await db
.collection("todos")
.where({
completed: false,
})
.count();
console.log("total record count:", result.total);
return result.total;
}
// Aggregation statistics example
async function aggregateStats() {
// Count the statistical quantity by priority grouping
const result = await db
.collection("todos")
.aggregate()
.group({
_id: "$priority",
count: { $sum: 1 },
})
.sort({
count: -1,
})
.end();
console.log("count by priority:", result.data);
// Output: [{ _id: 'high', count: 15 }, { _id: 'normal', count: 30 }, ...]
// Count the number of completed and ongoing tasks
const statusResult = await db
.collection("todos")
.aggregate()
.group({
_id: "$completed",
count: { $sum: 1 },
})
.end();
console.log("status statistics:", statusResult.data);
}
// Monitor data change in real time
function watchTodos() {
const listener = db
.collection("todos")
.where({
completed: false,
})
.orderBy("createdAt", "desc")
.limit(20)
.watch({
onChange: (snapshot) => {
console.log("data change:", snapshot.type);
if (snapshot.type === "init") {
// Initialize the data
console.log("initial data:", snapshot.docs);
} else {
// Incremental adjustment
snapshot.docChanges.forEach((change) => {
switch (change.dataType) {
case "add":
console.log("add document:", change.doc);
break;
case "update":
console.log("update document:", change.doc);
break;
case "remove":
console.log("delete document:", change.docId);
break;
}
});
}
},
onError: (error) => {
console.error("Listen error:", error);
},
});
// Return listener for subsequent close
return listener;
}
// Usage example
const listener = watchTodos();
// Close listener when needed
// listener.close();
// Complete error handling example
async function safeDbOperation() {
try {
// Query operation
const result = await db
.collection("todos")
.where({ completed: false })
.get();
console.log("query succeeded:", result.data);
return { success: true, data: result.data };
} catch (error) {
// Error Handling
console.error("Database operation failed:", error);
switch (error.code) {
case "PERMISSION_DENIED":
console.error(
"Insufficient permissions, please check security rule configuration"
);
break;
case "INVALID_PARAM":
console.error("Parameter error, check query condition");
break;
case "DATABASE_NOT_FOUND":
console.error("Database or collection not found");
break;
case "NETWORK_ERROR":
console.error("Network error, check the network");
break;
default:
console.error("Unknown error:", error.message);
}
return { success: false, error: error.message };
}
}
//Operation with retry
async function retryOperation(operation, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await operation();
} catch (error) {
console.warn(`Operation failed, retry ${i + 1}...`);
if (i === maxRetries - 1) throw error;
//Wait and retry later
await new Promise((resolve) => setTimeout(resolve, 1000 * (i + 1)));
}
}
}
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.
参数
Database configuration object (optional)
返回
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.
参数
Collection Name
返回
Creation result
示例
collection
db.collection(collName: string): CollectionReference
Retrieve collection reference for subsequent data operations.
参数
Collection Name
返回
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.
参数
Unique identifier of the document, supports string or number data type
返回
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
参数
The data object to be added, supporting nested objects, arrays, geographic locations and other data types
返回
示例
Query data
get
async get(): Promise<GetResult>
Get query results, return the document list that matches the condition.
-Return up to 100 records by default
- Support returning a maximum of 1000 records (set via limit).
参数
无参数
返回
示例
where
where(condition: object): Query
Set query conditions, support various operators to perform complex condition filtering.
-Query condition must be object type -The value of the condition object cannot all be undefined
参数
The query condition object, supporting equivalent matching, operator matching, nested field matching and other types
返回
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.
参数
无参数
返回
示例
orderBy
orderBy(fieldPath: string, direction: 'asc' | 'desc'): Query
Set the sorting method of query results.
参数
Sorting field path
Sorting order: asc ascending order, desc descending order
返回
Query object, can proceed with chained call
示例
limit
limit(max: number): Query
Set the maximum record count returned by the query.
- Default limit: 100 -supports up to 1000
参数
Maximum return record count, must be a positive integer, maximum value of 1000
返回
Query object, can proceed with chained call
示例
skip
skip(offset: number): Query
Set the query result offset for pagination queries.
参数
Offset, must be a non-negative integer
返回
Query object, can proceed with chained call
示例
field
field(projection: object): Query | DocumentReference
Specify the fields to return.
参数
Field projection object. true means return this field, false means do not return
返回
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.
Refer to the aggregate query for aggregation grammar.
参数
无参数
返回
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.
When querying a geolocation field, create a geo-indexing, otherwise the query will fail
参数
Nearby queries, return results sorted by distance
Region query, return results within the specified region
Intersect query, return results that intersect with the specified geometric shape
返回
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_idfield
参数
The data object to be updated, supporting updates to common fields and operators
返回
示例
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
参数
The data object to be set will replace all existing document content and cannot contain update operators
返回
示例
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()
When deleting in batches, the offset, limit, projection, and orderBy parameters will be ignored.
参数
无参数
返回
示例
Operator
Query operator
Get the query operator via db.command to build complex query conditions.
参数
返回
无参数
示例
Update operator
Get the update operator via db.command for execution of complex update operations.
参数
返回
无参数
示例
Transaction Operations
Support atomic operations on multiple documents to underwrite data consistency.
-Support only server-side use, not supported on the client.
- Please use the Node.js adapter for use in Node.js
startTransaction
async db.startTransaction(): Promise<Transaction>
Start a new 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.
参数
Transactional callback function, perform transaction operations in the function
Retry count for transaction conflicts, defaults to 3
返回
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.
参数
返回
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.
-Only the administrator can call the API -During execution in a transaction, any command failure would cause the entire transaction rollback.
参数
返回
示例
Other functions
serverDate
db.serverDate(options?: { offset?: number }): ServerDate
Get server time.
参数
返回
Server time object
示例
RegExp
db.RegExp({ regexp: string, options?: string }): RegExp
Create a regular expression object for fuzzy query.
参数
返回
regular expression object
示例
Aggregation Operator
Obtain aggregation operators through db.command.aggregate for expression calculation in the aggregation pipeline.
| Category | Operator |
|---|---|
| Arithmetic Operator | abs, add, ceil, divide, exp, floor, ln, log, log10, mod, multiply, pow, sqrt, subtract, trunc |
| Array Operator | arrayElemAt, arrayToObject, concatArrays, filter, in, indexOfArray, isArray, map, range, reduce, reverseArray, size, slice, zip |
| Boolean Operator | and, not, or |
| Comparison Operator | cmp, eq, gt, gte, lt, lte, neq |
| Conditional Operator | cond, ifNull, switch |
| Date Operator | dateFromParts, dateFromString, dayOfMonth, dayOfWeek, dayOfYear, isoDayOfWeek, isoWeek, isoWeekYear, millisecond, minute, month, second, hour, week, year |
| String Operator | concat, dateToString, indexOfBytes, indexOfCP, split, strLenBytes, strLenCP, strcasecmp, substr, substrBytes, substrCP, toLower, toUpper |
| Set Operator | allElementsTrue, anyElementTrue, setDifference, setEquals, setIntersection, setIsSubset, setUnion |
| Object Operator | mergeObjects, objectToArray |
| Grouping Operator | addToSet, avg, first, last, max, min, push, stdDevPop, stdDevSamp, sum |
| Other | literal, let, meta |