文档型数据库
文档型数据库(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}');
final db = app.database();
final _ = db.command;
final res = await db
.collection('todos')
.where({'completed': false, 'priority': _.inList(['high', 'medium'])})
.orderBy('createdAt', OrderDirection.desc)
.limit(10)
.get();
print('查询结果: ${res.data}');
final db = app.database();
final _ = db.command;
// 更新单个文档,字段自增
await db.collection('todos').doc('doc-id').update({'count': _.inc(1)});
// 删除单个文档
await db.collection('todos').doc('doc-id').remove();
final db = app.database();
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();
}
database
CloudBaseDatabase app.database({String? instance, String? database})
获取文档型数据库实例。可选参数 instance(实例 ID)与 database(数据库名称)用于指定要访问的数据库,两者均可省略,省略时默认使用 (default)(即默认实例的默认数据库)。仅当需要访问非默认的实例或数据库时才需显式传入。
参数
实例 ID,默认为 (default)
数据库名称,默认为 (default)
返回
数据库实例,提供 collection、command、Geo、startTransaction 等能力
示例
- 基本初始化
- 指定数据库配置
final db = app.database();
final db = app.database(instance: 'my-instance', database: 'my-db');
createCollection
Future<DbCreateCollectionResult> db.createCollection(String collName)
创建集合。
参数
集合名称
返回
示例
- 创建集合
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。
参数
集合名称
返回
集合引用
示例
- 获取集合引用
- 链式调用
final collection = db.collection('todos');
final res = await db
.collection('todos')
.where({'completed': false})
.orderBy('createdAt', OrderDirection.desc)
.limit(10)
.get();
add
Future<DbAddResult> collection.add(dynamic data)
向集合中添加记录,支持单条(Map)和批量(List)新增。
参数
文档数据,传入 Map 为单条新增,传入 List 为批量新增
返回
示例
- 单条新增
- 批量新增
final res = await db.collection('todos').add({
'title': '学习 CloudBase',
'completed': false,
'createdAt': DateTime.now(),
});
print('新增文档 ID: ${res.id}');
final res = await db.collection('todos').add([
{'title': '任务一', 'completed': false},
{'title': '任务二', 'completed': true},
]);
print('新增文档 ID 列表: ${res.ids}');
doc
DocumentReference collection.doc(dynamic docId)
获取文档引用,可在其上调用 get、update、set、remove、field。
参数
文档 ID
返回
文档引用
示例
- 获取文档引用
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 指令进行复杂条件筛选。
参数
查询条件对象,支持等值匹配、操作符匹配、嵌套字段匹配等
返回
查询对象,可链式调用 orderBy、limit、skip、field、get、count、update、remove 等方法
示例
- 基本查询
- 复杂条件查询
final res = await db
.collection('todos')
.where({'completed': false, 'priority': 'high'})
.get();
print('查询结果: ${res.data}');
final _ = db.command;
final res = await db
.collection('todos')
.where({
'age': _.gt(18),
'tags': _.inList(['技术', '学习']),
'createdAt': _.gte(DateTime.now().subtract(const Duration(days: 7))),
})
.orderBy('createdAt', OrderDirection.desc)
.limit(10)
.get();
print('查询结果: ${res.data}');
orderBy
Query collection.orderBy(String field, OrderDirection direction)
设置排序规则,direction 取值为 OrderDirection.asc 或 OrderDirection.desc。可多次调用组合多字段排序。
参数
排序字段
排序方向:OrderDirection.asc(升序)或 OrderDirection.desc(降序)
返回
查询对象,可继续链式调用
示例
- 示例
final res = await db
.collection('todos')
.orderBy('createdAt', OrderDirection.desc)
.get();
limit
Query collection.limit(int max)
设置返回数量上限。
参数
返回记录数量上限
返回
查询对象,可继续链式调用
示例
- 示例
final res = await db.collection('todos').limit(10).get();
skip
Query collection.skip(int offset)
设置跳过的记录数量,常用于分页。
参数
跳过的记录数量(偏移量)
返回
查询对象,可继续链式调用
示例
- 分页查询
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 方法。
参数
字段投影,如 {'title': true, 'content': false}
返回
查询对象,可继续链式调用
示例
- 示例
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 为空列表)。
参数
无参数
返回
示例
- 查询集合
- 查询单个文档
final res = await db.collection('todos').get();
print('共 ${res.data.length} 条记录');
final res = await db.collection('todos').doc('doc-id').get();
if (res.data.isNotEmpty) {
print('文档内容: ${res.data.first}');
}
count
Future<DbCountResult> collection.count()
Future<DbCountResult> query.count()
统计匹配条件的文档数量。
参数
无参数
返回
示例
- 示例
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 时返回更新后的文档。
参数
更新数据,可使用 db.command 更新指令(如 _.inc、_.set、_.push 等)
仅文档引用 update 支持,为 true 时返回更新后的文档,默认 false
返回
示例
- 更新单个文档
- 批量更新
final _ = db.command;
final res = await db
.collection('todos')
.doc('doc-id')
.update({'count': _.inc(1), 'completed': true}, returnDoc: true);
print('更新后的文档: ${res.doc}');
final res = await db
.collection('todos')
.where({'completed': false})
.update({'archived': true});
print('更新了 ${res.updated} 条记录');
set
Future<DbUpdateResult> doc.set(Map<String, dynamic> data)
设置文档数据(完全替换,文档不存在则创建)。
参数
文档完整数据,将完全替换原文档
返回
示例
- 示例
final res = await db.collection('todos').doc('doc-id').set({
'title': '重置后的任务',
'completed': false,
});
remove
Future<DbRemoveResult> query.remove()
Future<DbRemoveResult> doc.remove()
删除文档。在 Query 上调用为批量删除匹配条件的文档;在文档引用上调用为删除单个文档。
参数
无参数
返回
示例
- 删除单个文档
- 批量删除
final res = await db.collection('todos').doc('doc-id').remove();
print('删除了 ${res.deleted} 条记录');
final res = await db
.collection('todos')
.where({'completed': true})
.remove();
print('删除了 ${res.deleted} 条记录');
command
DbCommand get db.command
获取查询/更新指令(对应 JS SDK 的 db.command,通常简写为 _)。支持比较、逻辑、字段/数组、更新、地理位置等操作符。
参数
无参数
返回
指令对象,用于构建查询条件与更新操作
示例
- 比较与逻辑操作符
- 字段与数组操作符
- 更新操作符
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();
final _ = db.command;
// exists / mod / all / elemMatch / size
await db.collection('todos').where({
'tags': _.all(['技术', '学习']),
'assignee': _.exists(true),
}).get();
final _ = db.command;
// set / remove / inc / mul / min / max / rename / bit
await db.collection('todos').doc('doc-id').update({
'count': _.inc(1),
'weight': _.mul(2),
'deprecatedField': _.remove(),
});
// 数组更新:push / pop / shift / unshift / pull / pullAll / addToSet
await db.collection('todos').doc('doc-id').update({
'tags': _.push('新标签'),
'members': _.addToSet('user-1'),
});
aggregate
Aggregate collection.aggregate()
获取聚合操作对象,链式添加聚合阶段后调用 end() 执行。支持 match、group、sort、project、limit、skip、unwind、lookup、addFields、count、sample、bucket、bucketAuto、geoNear、replaceRoot、sortByCount 以及自定义 stage。
参数
无参数
返回
聚合操作对象,链式添加阶段后调用 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 回滚。
参数
无参数
返回
示例
- 转账事务
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 风格数据库命令(批量),仅管理员可调用。
参数
命令对象数组
事务 ID(可选,在事务中执行所有命令)
返回
示例
- 示例
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为毫秒偏移量。
参数
无参数
返回
地理位置命名空间
示例
- 地理位置查询
- 正则模糊查询
- 服务端时间
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();
final res = await db.collection('todos').where({
'title': db.RegExp(regexp: '学习', options: 'i'),
}).get();
// 写入服务端当前时间
await db.collection('todos').add({
'title': '任务',
'createdAt': db.serverDate(),
});