微信小程序云开发(2)数据库,高级查询功能
一、初始化云开发环境
首先,确保您已经在微信小程序中初始化了云开发环境。这通常包括在微信开发者工具中启用云开发,并创建一个新的云环境。然后,您可以在小程序代码中通过以下方式初始化云开发环境:
wx.cloud.init({
env: 'your-env-id', // 替换为您的云环境ID
});
const db = wx.cloud.database();
二、基本查询示例
1. 查询集合中的所有文档
假设您有一个名为“products”的集合,您想查询其中的所有文档:
db.collection('products').get().then(res => {
console.log('查询结果', res.data); // 输出查询结果
}).catch(err => {
console.error('查询失败', err);
});
2. 根据特定字段查询文档
假设您想查询“products”集合中,所有名为“iPhone”的产品:
db.collection('products').where({
name: 'iPhone'
}).get().then(res => {
console.log('查询结果', res.data); // 输出查询结果
}).catch(err => {
console.error('查询失败', err);
});
三、高级查询示例
1. 复合查询
假设您想查询“products”集合中,价格大于1000且小于5000的电子产品:
const _ = db.command;
db.collection('products').where({
price: _.gt(1000).and(_.lt(5000)),
type: '电子产品'
}).get().then(res => {
console.log('查询结果', res.data); // 输出查询结果
}).catch(err => {
console.error('查询失败', err);
});
2. 使用逻辑运算符
您可以使用or
、and
等逻辑运算符来构建更复杂的查询条件。例如,查询价格大于1000或名称为“iPhone”的产品:
const _ = db.command;
db.collection('products').where({
_or: [
{ price: _.gt(1000) },
{ name: 'iPhone' }
]
}).get().then(res => {
console.log('查询结果', res.data); // 输出查询结果
}).catch(err => {
console.error('查询失败', err);
});
3. 排序和分页
假设您想查询“products”集合中,价格大于1000的电子产品,并按价格降序排列,且只获取前10条记录:
const _ = db.command;
db.collection('products').where({
price: _.gt(1000),
type: '电子产品'
}).orderBy('price', 'desc')
.skip(0) // 跳过0条记录
.limit(10) // 限制返回10条记录
.get().then(res => {
console.log('查询结果', res.data); // 输出查询结果
}).catch(err => {
console.error('查询失败', err);
});
四、其他查询需求功能
1. 查询特定ID的文档
假设您知道某个文档的ID,并想查询该文档:
db.collection('products').doc('specific-doc-id').get().then(res => {
console.log('查询结果', res.data); // 输出查询结果
}).catch(err => {
console.error('查询失败', err);
});
2. 查询字段值在给定数组中的文档
假设您想查询“products”集合中,类型为“电子产品”或“家居用品”的文档:
db.collection('products').where({
type: _.in(['电子产品', '家居用品'])
}).get().then(res => {
console.log('查询结果', res.data); // 输出查询结果
}).catch(err => {
console.error('查询失败', err);
});
3. 聚合查询(如统计记录数量)
虽然微信小程序云开发数据库不直接支持SQL中的聚合查询(如COUNT
),但您可以通过其他方式实现类似的功能。例如,查询“products”集合中,类型为“电子产品”的文档数量:
db.collection('products').where({
type: '电子产品'
}).count().then(res => {
console.log('文档数量', res.total); // 输出文档数量
}).catch(err => {
console.error('查询失败', err);
});