跳到主要内容

查询数据

初始化 SDK

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

const app = cloudbase.init({
env: "your-env-id",
});

const db = app.database();
const _ = db.command; // 获取查询指令

单条查询

通过文档 ID 查询指定记录。

参数说明

参数类型必填说明
docIdstring文档的唯一标识符

代码示例

// 根据文档 ID 查询单条记录
const result = await db.collection('todos')
.doc('docId')
.get()

返回结果

{
data: [{
_id: "todo-id-123",
title: "学习 CloudBase",
completed: false,
// ... 其他字段
}],
}

多条查询

查询集合中的多条记录,支持条件筛选、排序、分页等。

⚠️ 注意:get() 方法默认返回100条数据,如需更多数据请使用分页

参数说明

方法参数类型必填说明
where()object查询条件,支持操作符
orderBy()string, string排序字段和方向('asc' 或 'desc')
limit()number限制返回记录数,默认 100 条,最多返回 1000 条
skip()number跳过记录数,用于分页
field()object指定返回字段,true 表示返回,false 表示不返回
// 查询所有记录
const result = await db.collection('todos').get()

// 条件查询
const result = await db.collection('todos')
.where({
completed: false,
priority: 'high'
})
.get()

复杂查询

const _ = db.command

// 复杂条件查询
const result = await db.collection('todos')
.where({
// 年龄大于 18
age: _.gt(18),
// 标签包含 '技术'
tags: _.in(['技术', '学习']),
// 创建时间在最近一周内
createdAt: _.gte(new Date(Date.now() - 7 * 24 * 60 * 60 * 1000))
})
.orderBy('createdAt', 'desc') // 按创建时间倒序
.limit(10) // 限制 10 条
.skip(0) // 跳过 0 条(分页)
.field({ // 只返回指定字段
title: true,
completed: true,
createdAt: true
})
.get()

分页查询

// 分页查询示例
const pageSize = 10
const pageNum = 1

const result = await db.collection('todos')
.orderBy('createdAt', 'desc')
.skip((pageNum - 1) * pageSize)
.limit(pageSize)
.get()

聚合查询

聚合语法具体参考 聚合查询

// 统计查询
const result = await db.collection('todos')
.aggregate()
.group({
_id: '$priority',
count: {
$sum: 1
}
})
.end()

console.log('按优先级统计:', result.list)

地理位置查询

⚠️ 注意:对地理位置字段进行查询时,请建立地理位置索引,否则查询将失败

const _ = db.command
// 查询附近的用户(按距离排序)
db.collection("users").where({
location: _.geoNear({
geometry: new db.Geo.Point(116.404, 39.915), // 天安门坐标
maxDistance: 1000, // 最大距离1000米
minDistance: 0 // 最小距离0米
})
}).get()

// 查询指定区域内的用户
db.collection("users").where({
location: _.geoWithin({
geometry: polygon // 使用上面定义的多边形
})
}).get()

// 查询与路径相交的用户
db.collection("users").where({
location: _.geoIntersects({
geometry: line // 使用上面定义的路径
})
}).get()