13、云数据库进阶操作
强制转整型函数:parseInt()
1. 数据排序
关键字:orderBy ,在做排序时接收两个参数。
- 根据哪个字段排序
- 排序规则(升序或降序)升序用asc,降序用desc
案例:将学生信息按成绩升序排列,两个代码文件wxml,js
代码:
<!--pages/demo04/demo04.wxml-->
<view >
<view>查询结果显示</view>
<view wx:for="{{stu}}" wx:key="_id">
<view>ID: {{item._id}} ,姓名: {{item.name}} ,性别: {{item.sex}},成绩: {{item.score}}</view>
</view>
</view>
<button bindtap="orderStu" type="primary">升序记录</button>
// pages/demo04/demo04.js
Page({
data: {
stu:{}
},
onLoad(){
wx.cloud.database().collection('stu')
.get()
.then( res =>{
console.log("学生信息请求成功",res)
this.setData({
stu:res.data
})
})
.catch( err =>{
console.log('学生信息请求失败',err)
})
},
orderStu(){
wx.cloud.database().collection('stu').orderBy('score','asc')
.get()
.then( res =>{
this.setData({
stu:res.data
})
})
.catch( err =>{
console.log('学生信息排序请求失败',err)
})
}
})
运行截图:
2.返回指定条数数据limit
限定返回条数。注意:limit在小程序端默认最大上限为20,在云函数端默认最大上限为1000.
例如:只返回3条数据代码。
wx.cloud.database().collection('stu').limit(3)
.get()
.then( res =>{
console.log("学生信息请求成功",res)
this.setData({
stu:res.data
})
})
.catch( err =>{
console.log('学生信息请求失败',err)
})
3.分页方法skip
指定查询返回结果时从指定序列后的结果开始返回。
比如我们有30条数据,每次返回10条数据,那么可以分为3次返回。
第一次:limit(10).skip(0)
第二次:limit(10).skip(10)
第三次:limit(10).skip(20)
wx.cloud.database().collection('stu').skip(3)
.get()
.then( res =>{
console.log("学生信息请求成功",res)
this.setData({
stu:res.data
})
})
.catch( err =>{
console.log('学生信息请求失败',err)
4.数据库高级操作符command
gt查询成绩大于指定值的学生信息
let db = wx.cloud.database()
db.collection('stu')
.where({
score:db.command.gt(80) //数值大于80
})
.get()
.then( res =>{
console.log("学生信息请求成功",res)
this.setData({
stu:res.data
})
})
.catch( err =>{
console.log('学生信息请求失败',err)
})
gte查询成绩大于等于指定值的学生信息
let db = wx.cloud.database()
db.collection('stu')
.where({
score:db.command.gte(80) //数值大于80
})
.get()
.then( res =>{
console.log("学生信息请求成功",res)
this.setData({
stu:res.data
})
})
.catch( err =>{
console.log('学生信息请求失败',err)
})
lt查询成绩小于指定值的学生信息
let db = wx.cloud.database()
db.collection('stu')
.where({
score:db.command.lt(80) //数值大于80
})
.get()
.then( res =>{
console.log("学生信息请求成功",res)
this.setData({
stu:res.data
})
})
.catch( err =>{
console.log('学生信息请求失败',err)
})
lte查询成绩小于等于指定值的学生信息
let db = wx.cloud.database()
db.collection('stu')
.where({
score:db.command.lte(80) //数值大于80
})
.get()
.then( res =>{
console.log("学生信息请求成功",res)
this.setData({
stu:res.data
})
})
.catch( err =>{
console.log('学生信息请求失败',err)
})
查询大于多少且小于多少的学生信息
用到了查询-逻辑操作符,有and or not nor
案例,查询成绩大于80小于90的学生信息
let db = wx.cloud.database()
let _ = db.command
db.collection('stu')
.where(_.and(
[
{
score:_.gt(80)
},//大于80
{
score:_.lt(90)
}//小于90
]
))
.get()
.then( res =>{
console.log("学生信息请求成功",res)
this.setData({
stu:res.data
})
})
.catch( err =>{
console.log('学生信息请求失败',err)
})