跳到主要内容

文档型数据库

文档型数据库(NoSQL)提供 JS SDK 风格的链式调用,通过 app.database() 获取实例。支持集合与文档的增删改查、复杂条件查询、聚合、事务等能力,并已与 HTTP API 全面对齐。

final app = await CloudBase.init(env: 'your-env-id');
final db = app.database();

// 单条新增
final addRes = await db.collection('todos').add({
'title': '学习 CloudBase',
'completed': false,
'createdAt': DateTime.now(),
});
print('新增文档 ID: ${addRes.id}');

database​

CloudBaseDatabase app.database({String? instance, String? database})

获取文档型数据库实例。可选参数 instance(实例 ID)与 database(数据库名称)用于指定要访问的数据库,两者均可省略,省略时默认使用 (default)(即默认实例的默认数据库)。仅当需要访问非默认的实例或数据库时才需显式传入。

参数

instance
String?

实例 ID,默认为 (default)

database
String?

数据库名称,默认为 (default)

返回

CloudBaseDatabase
CloudBaseDatabase

数据库实例,提供 collection、command、Geo、startTransaction 等能力

示例

final db = app.database();

createCollection​

Future<DbCreateCollectionResult> db.createCollection(String collName)

创建集合。

参数

collName
String

集合名称

返回

Future
DbCreateCollectionResult

示例

final result = await db.createCollection('todos');
if (result.isSuccess) {
print('集合创建成功');
}

collection​

CollectionReference db.collection(String collName)

获取集合引用,可在其上链式调用 where、orderBy、limit、skip、field 等查询方法,或调用 doc、add、get、count、aggregate。

参数

collName
String

集合名称

返回

CollectionReference
CollectionReference

集合引用

示例

final collection = db.collection('todos');

add​

Future<DbAddResult> collection.add(dynamic data)

向集合中添加记录,支持单条(Map)和批量(List)新增。

参数

data
dynamic

文档数据,传入 Map 为单条新增,传入 List 为批量新增

返回

Future
DbAddResult

示例

final res = await db.collection('todos').add({
'title': '学习 CloudBase',
'completed': false,
'createdAt': DateTime.now(),
});
print('新增文档 ID: ${res.id}');

doc​

DocumentReference collection.doc(dynamic docId)

获取文档引用,可在其上调用 get、update、set、remove、field。

参数

docId
dynamic

文档 ID

返回

DocumentReference
DocumentReference

文档引用

示例

final docRef = db.collection('todos').doc('doc-id');
final res = await docRef.get();
print(res.data);

where​

Query collection.where(Map<String, dynamic> condition)

设置查询条件,支持等值匹配以及通过 db.command 指令进行复杂条件筛选。

参数

condition
Map<String, dynamic>

查询条件对象,支持等值匹配、操作符匹配、嵌套字段匹配等

返回

Query
Query

查询对象,可链式调用 orderBy、limit、skip、field、get、count、update、remove 等方法

示例

final res = await db
.collection('todos')
.where({'completed': false, 'priority': 'high'})
.get();

print('查询结果: ${res.data}');

orderBy​

Query collection.orderBy(String field, OrderDirection direction)

设置排序规则,direction 取值为 OrderDirection.asc 或 OrderDirection.desc。可多次调用组合多字段排序。

参数

field
String

排序字段

direction
OrderDirection

排序方向:OrderDirection.asc(升序)或 OrderDirection.desc(降序)

返回

Query
Query

查询对象,可继续链式调用

示例

final res = await db
.collection('todos')
.orderBy('createdAt', OrderDirection.desc)
.get();

limit​

Query collection.limit(int max)

设置返回数量上限。

参数

max
int

返回记录数量上限

返回

Query
Query

查询对象,可继续链式调用

示例

final res = await db.collection('todos').limit(10).get();

skip​

Query collection.skip(int offset)

设置跳过的记录数量,常用于分页。

参数

offset
int

跳过的记录数量(偏移量)

返回

Query
Query

查询对象,可继续链式调用

示例

const pageSize = 10;
const pageNum = 2;

final res = await db
.collection('todos')
.orderBy('createdAt', OrderDirection.desc)
.skip((pageNum - 1) * pageSize)
.limit(pageSize)
.get();

print('第 $pageNum 页数据: ${res.data}');
print('偏移量: ${res.offset}, 每页数量: ${res.limit}');

field​

Query collection.field(Map<String, dynamic> projection)

指定查询返回的字段,true 表示返回,false 表示不返回。文档引用 doc 也支持 field 方法。

参数

projection
Map<String, dynamic>

字段投影,如 {'title': true, 'content': false}

返回

Query
Query

查询对象,可继续链式调用

示例

final res = await db
.collection('todos')
.where({'completed': false})
.field({'title': true, 'completed': true, 'content': false})
.get();

get​

Future<DbGetResult> collection.get()
Future<DbGetResult> query.get()
Future<DbGetResult> doc.get()

获取查询结果。在集合引用上调用为无条件查询,在 Query 上调用返回匹配文档列表,在文档引用上调用返回单个文档(文档不存在时 data 为空列表)。

参数

无参数

返回

Future
DbGetResult

示例

final res = await db.collection('todos').get();
print('共 ${res.data.length} 条记录');

count​

Future<DbCountResult> collection.count()
Future<DbCountResult> query.count()

统计匹配条件的文档数量。

参数

无参数

返回

Future
DbCountResult

示例

final res = await db
.collection('todos')
.where({'completed': false})
.count();
print('未完成任务数量: ${res.total}');

update​

Future<DbUpdateResult> query.update(Map<String, dynamic> data)
Future<DbUpdateResult> doc.update(Map<String, dynamic> data, {bool returnDoc = false})

更新文档。在 Query 上调用为批量更新匹配条件的文档;在文档引用上调用为合并更新单个文档,returnDoc 为 true 时返回更新后的文档。

参数

data
Map<String, dynamic>

更新数据,可使用 db.command 更新指令(如 _.inc、_.set、_.push 等)

returnDoc
bool

仅文档引用 update 支持,为 true 时返回更新后的文档,默认 false

返回

Future
DbUpdateResult

示例

final _ = db.command;

final res = await db
.collection('todos')
.doc('doc-id')
.update({'count': _.inc(1), 'completed': true}, returnDoc: true);
print('更新后的文档: ${res.doc}');

set​

Future<DbUpdateResult> doc.set(Map<String, dynamic> data)

设置文档数据(完全替换,文档不存在则创建)。

参数

data
Map<String, dynamic>

文档完整数据,将完全替换原文档

返回

Future
DbUpdateResult

示例

final res = await db.collection('todos').doc('doc-id').set({
'title': '重置后的任务',
'completed': false,
});

remove​

Future<DbRemoveResult> query.remove()
Future<DbRemoveResult> doc.remove()

删除文档。在 Query 上调用为批量删除匹配条件的文档;在文档引用上调用为删除单个文档。

参数

无参数

返回

Future
DbRemoveResult

示例

final res = await db.collection('todos').doc('doc-id').remove();
print('删除了 ${res.deleted} 条记录');

command​

DbCommand get db.command

获取查询/更新指令(对应 JS SDK 的 db.command,通常简写为 _)。支持比较、逻辑、字段/数组、更新、地理位置等操作符。

参数

无参数

返回

DbCommand
DbCommand

指令对象,用于构建查询条件与更新操作

示例

final _ = db.command;

// eq / neq / gt / gte / lt / lte / inList / nin
await db.collection('todos').where({'age': _.gte(18)}).get();

// and / or / not / nor
await db.collection('todos').where({
'priority': _.or([_.eq('high'), _.eq('medium')]),
}).get();

aggregate​

Aggregate collection.aggregate()

获取聚合操作对象,链式添加聚合阶段后调用 end() 执行。支持 match、group、sort、project、limit、skip、unwind、lookup、addFields、count、sample、bucket、bucketAuto、geoNear、replaceRoot、sortByCount 以及自定义 stage。

参数

无参数

返回

Aggregate
Aggregate

聚合操作对象,链式添加阶段后调用 end() 执行

示例

final res = await db
.collection('todos')
.aggregate()
.match({'completed': true})
.group({
'_id': '\$priority',
'total': {'\$sum': 1},
})
.sort({'total': -1})
.end();

print('聚合结果: ${res.data}');

startTransaction​

Future<Transaction> db.startTransaction()

开启事务,返回事务对象。通过事务对象的 collection 获取事务内的集合引用进行操作,最后调用 commit 提交或 rollback 回滚。

参数

无参数

返回

Future
Transaction

示例

final _ = db.command;

final transaction = await db.startTransaction();
try {
await transaction.collection('accounts').doc('a').update({'balance': _.inc(-100)});
await transaction.collection('accounts').doc('b').update({'balance': _.inc(100)});
await transaction.commit();
} catch (e) {
await transaction.rollback();
}

runCommands​

Future<DbRunCommandsResult> db.runCommands({required List<Map<String, dynamic>> commands, String? transactionId})

执行 MongoDB 风格数据库命令(批量),仅管理员可调用。

参数

commands
List<Map<String, dynamic>>

命令对象数组

transactionId
String?

事务 ID(可选,在事务中执行所有命令)

返回

Future
DbRunCommandsResult

示例

final res = await db.runCommands(commands: [
{'find': 'todos', 'filter': {'completed': true}},
]);
print('执行结果: ${res.list}');

Geo​

GeoNamespace get db.Geo
DbRegExp db.RegExp({required String regexp, String? options})
DbServerDate db.serverDate({int offset = 0})

数据库辅助类型:地理位置命名空间 Geo、正则表达式 RegExp、服务端时间 serverDate。

  • Geo 支持 point、lineString、polygon、multiPoint、multiLineString、multiPolygon,配合指令 geoNear、geoWithin、geoIntersects 使用。
  • RegExp 用于模糊查询,options 如 i 表示忽略大小写。
  • serverDate 生成服务端时间,offset 为毫秒偏移量。

参数

无参数

返回

GeoNamespace
GeoNamespace

地理位置命名空间

示例

final _ = db.command;

// 查询距离指定坐标 5000 米内的记录
// geoNear 仅支持 geometry、maxDistance、minDistance 三个参数,不支持通过参数限制返回条数(例如 limit: 10)
// 如需限制返回条数,请在 where() 之后链式调用 limit(),如末尾的 .limit(10)
final res = await db.collection('places').where({
'location': _.geoNear(
geometry: db.Geo.point(116.397, 39.908),
maxDistance: 5000,
),
}).limit(10).get();