Document Database
createCollection
1. API Description
API feature: This API can create a collection.
API Declaration:
createCollection(collectionName: string): Promise<Object>
createCollectionIfNotExists(collectionName: string): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| CollectionName | Required | String | Collection name |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
4. Sample Code
const cloudbaseConfig = {
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
};
let { database } = new CloudBase(cloudbaseConfig);
async function test() {
let result = await database.createCollection("collectionName");
console.log(result);
}
test();
checkCollectionExists
1. API Description
API feature: Check if the collection exists
API declaration: checkCollectionExists(collectionName: string): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| - | Required | String | Collection name |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| Msg | No | String | Error message |
| Exists | Required | Boolean | Whether the collection already exists |
4. Sample Code
const cloudbaseConfig = {
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
};
let { database } = new CloudBase(cloudbaseConfig);
async function test() {
let result = await database.checkCollectionExists("collectionAlreadyExists");
if (result.Exists) {
// Collection exists
} else {
// Collection does not exist
}
}
test();
deleteCollection
1. API Description
API feature: Deletes a collection
API declaration: deleteCollection(collectionName: string): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| CollectionName | Required | String | Collection name |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| Exists | No | Boolean | Not returned if present; returns false if absent |
4. Sample Code
const cloudbaseConfig = {
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
};
let { database } = new CloudBase(cloudbaseConfig);
async function test() {
let result = await database.deleteCollection("collectionAlreadyExists");
if (result.Exists === false) {
// Collection does not exist
}
}
test();
updateCollection
1. API Description
API feature: This API can update a collection.
API declaration: updateCollection(collectionName: string, options: array): Promise<Object>
This API can update collections, but currently supports updating indexes.
⚠️ Currently, this API can only update indexes, including creation and deletion.
- If an index already exists during creation, it will be deleted first and then recreated.
- Since a single API call can create multiple indexes simultaneously, partial failures may occur (while others succeed), and the API will throw an exception.
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| collectionName | Required | String | Collection name |
| options | Required | Array<Option> | Configuration options |
Option
| Field | Required | Type | Description |
|---|---|---|---|
| CreateIndexes | No | Array<CreateIndex> | List of indexes to be created |
| DropIndexes | No | Array<DropIndex> | List of indexes to be deleted |
CreateIndex
| Field | Required | Type | Description |
|---|---|---|---|
| IndexName | Required | String | Index name |
| MgoKeySchema | Required | Array<MgoKeySchema> | Index rules |
MgoKeySchema
| Field | Required | Type | Description |
|---|---|---|---|
| MgoIsUnique | Required | boolean | Whether unique |
| MgoIndexKeys | Required | Array<MgoIndexKey> | List of fields included in the index |
MgoIndexKey
| Field | Required | Type | Description | Specifies the index name, uniqueness constraint, TTL index settings, and collation rules. |
|---|---|---|---|---|
| Name | Required | String | Index name | |
| Direction | Required | String | Index direction: 1 for ASC, -1 for DESC, 2d for bidirectional (must be placed first if present). Note: For geospatial indexes, set this value to "2dsphere". |
DropIndex
| Field | Required | Type | Description |
|---|---|---|---|
| IndexName | Required | String | Index name |
Two independent methods for updating indexes: creating and deleting. CreateIndexes and DropIndexes cannot be passed simultaneously in options.
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
4. Sample Code
Create a new index
const cloudbaseConfig = {
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
};
let { database } = new CloudBase(cloudbaseConfig);
async function test() {
let result = await database.updateCollection("collectionAlreadyExists", {
CreateIndexes: [
{
IndexName: "index_a",
MgoKeySchema: {
MgoIndexKeys: [
// 2d must be placed first
{ Name: "a_2d", Direction: "2d" },
{ Name: "a_1", Direction: "1" },
{ Name: "a_-1", Direction: "-1" },
],
MgoIsUnique: false,
},
},
{
IndexName: "index_b",
MgoKeySchema: {
MgoIndexKeys: [{ Name: "b_1", Direction: "2d" }],
MgoIsUnique: true,
},
},
{
IndexName: "index_to_be_delete",
MgoKeySchema: {
MgoIndexKeys: [{ Name: "xxx", Direction: "2d" }],
MgoIsUnique: true,
},
},
],
});
console.log(result);
}
test();
Delete Indexes
const cloudbaseConfig = {
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
};
let { database } = new CloudBase(cloudbaseConfig);
async function test() {
let result = await database.updateCollection("collectionAlreadyExists", {
DropIndexes: [{ IndexName: "index_to_be_delete" }],
});
console.log(result);
}
test();
describeCollection
1. API Description
API feature: Query collection details
API declaration: describeCollection(collectionName: string): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| CollectionName | Required | String | Collection name |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| IndexNum | Required | Number | Number of indexes |
| Indexes | Required | Array | Index list |
| Indexes[N].Name | Required | String | Index name |
| Indexes[N].Size | Required | String | Index size, unit: bytes |
| Indexes[N].Unique | Required | String | Whether the index is unique |
| Indexes[N].Keys | Required | Array | Index keys |
| Indexes[N].Keys[N].Name | Required | String | Key name |
| Indexes[N].Keys[N].Direction | Required | String | Index direction: 1: ASC, -1: DESC, 2d: bidirectional |
| Indexes[N].Accesses | Required | Array | Index usage information |
| Indexes[N].Accesses[N].Ops | Required | Number | Number of index hits |
| Indexes[N].Accesses[N].Since | Required | String | Start time of hit count |
4. Sample Code
const cloudbaseConfig = {
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
};
let { database } = new CloudBase(cloudbaseConfig);
async function test() {
let result = await database.describeCollection("collectionAlreadyExists");
const { Indexes } = result;
for (let index in Indexes) {
console.log(index); // Iterate through all indexes
}
}
test();
listCollections
1. API Description
API feature: Query collection details
API declaration: listCollections(options: object): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| MgoOffset | No | Number | Optional, offset |
| MgoLimit | No | Number | Optional, quantity limit |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| Collections | Required | Array | Collection list |
| Collections[N].CollectionName | Required | String | Collection name |
| Collections[N].Count | Required | Number | Number of documents in the collection |
| Collections[N].Size | Required | Number | Size of the collection in bytes |
| Collections[N].IndexCount | Required | Number | Number of indexes in the collection |
| Collections[N].IndexSize | Required | Number | Size of indexes in the collection, in bytes |
| Pager | Required | Object | Pagination information for this query |
| Pager.Offset | Required | Number | Offset |
| Pager.Limit | Required | Number | Limit |
| Pager.Total | Required | Number | Total number of collections |
4. Sample Code
const cloudbaseConfig = {
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
};
let { database } = new CloudBase(cloudbaseConfig);
async function test() {
let result = await database.listCollections({
MgoOffset: 100,
MgoLimit: 10,
});
const { Collections } = result;
for (let collection in Collections) {
console.log(collection); // Iterate through all collections
}
}
checkIndexExists
1. API Description
API feature: Check whether the index exists
API declaration: checkIndexExists(collectionName: string, indexName: string): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| collectionName | Required | String | Collection name |
| indexName | Required | String | Index name |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| Exists | Required | Boolean | Whether the index exists |
4. Sample Code
const cloudbaseConfig = {
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
};
let { database } = new CloudBase(cloudbaseConfig);
async function test() {
let result = await database.checkIndexExists(
"collectionAlreadyExists",
"index_to_be_delete",
);
const { Exists } = result;
if (Exists === true) {
// The index exists
}
}
test();
import
1. API Description
API Feature: Import Data
API declaration: import(collectionName: string, file: object, options: object): Promise<Object>
Note:
- The API returns immediately, and the migration status (success|failure) can be queried via migrateStatus.
- Importing data requires first uploading the file to COS in the environment (same EnvId), so it will create objects in COS.
- Because the successful return of this function only indicates that the upload is successful, the import operation begins after uploading. This API cannot determine whether the import is complete. Therefore, the object needs to be manually deleted after use.
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| collectionName | Required | String | Collection name |
| file | Required | Array | Data, one of the following methods must be selected |
| ⁃ FilePath | Required | String | Local data file path |
| ⁃ ObjectKey | Required | String | COS Key in the current environment |
| options | Optional | Array | Optional parameters |
| ⁃ ObjectKeyPrefix | Optional | String | COS Key prefix, default is tmp/db-imports/ |
| FileType | Optional | String | File type: csv or json. If this parameter is not passed, it defaults to the file extension. Ensure to use the correct file extension. |
| ⁃ StopOnError | Optional | Boolean | whether to stop the import when encountering errors |
| ⁃ ConflictMode | Optional | String | Conflict resolution method: insert or upsert |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| JobId | Required | Number | Task ID, used to query migration status in the migrateStatus API |
4. Sample Code
const cloudbaseConfig = {
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
};
let { database } = new CloudBase(cloudbaseConfig);
async function test() {
let res = await database.import(
"collectionAlreadyExists",
{
ObjectKey: "data.csv",
},
{
// "FileType" : "csv",
StopOnError: true,
ConflictMode: "upsert",
},
);
const { JobId } = res;
console.log(JobId);
}
test();
export
1. API Description
API feature: export data, migration status (success|failure) can be queried via migrateStatus.
API declaration: export(collectionName: string, file: object, options: object): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| collectionName | Required | String | Collection name |
| file | Required | Array | Data, one of the following methods must be selected |
| ⁃ ObjectKey | Required | String | COS Key in the current environment |
| options | Optional | Array | Optional parameters |
| FileType | Optional | String | File type: csv or json. If this parameter is not passed, it defaults to the file extension. Ensure to use the correct file extension. |
| ⁃ Query | No | String | JSON string, supports mongo commands. Example: '{ a: { gte: 3 } }'. Compatible with mongodb query syntax |
| Skip | No | Number | offset |
| ⁃ Limit | Optional | Number | Limit |
| ⁃ Sort | Optional | Number | JSON string. If an index exists, sorting is not supported. The dataset length must be less than 32 MB. |
| ⁃ Fields | Optional | String | String, fields separated by commas. Required when FileType=csv. |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| JobId | Required | Number | Task ID, used to query migration status in the migrateStatus API |
4. Sample Code
const cloudbaseConfig = {
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
};
let { database } = new CloudBase(cloudbaseConfig);
async function test() {
let result = await database.export(
"users",
{
ObjectKey: "users.json",
},
{
Fields: "_id,name",
Query: '{"name":{"$exists":true}}',
Sort: '{"name": -1}',
Skip: 0,
Limit: 1000,
},
);
const { JobId } = res;
console.log(JobId);
}
test();