微信云数据库的语法,和关系型数据库的SQL语法非常类似。
文本中的代码,除了指明为小程序和云函数的,其它都在云开发的数据库脚本中运行。
环境
- 微信开发者工具 Stable 1.06.2303220
- 云开发控制台 v1.5.47
基本概念
Database
Database就是数据库。
云开发控制台的脚本,自带 db
变量。
小程序端:
const db = wx.cloud.database()
云函数端:
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
Collection
Collection就是表。
使用database的 collection()
函数获取表,例如:
db.collection('table0508').get()
注:参数是collection的名字。
注: get()
是获取数据的请求。
Document
Document就是记录。
使用Collection的 doc()
函数获取记录,例如:
db.collection('table0508').doc('4429a59c64590fd4001e61046143358f').get()
注:参数是记录的 _id
值。
查询条件
where
where
类似于SQL语法中的 where
,例如:
db.collection("table0508").where({
sex: "女"
}).get()
orderBy
orderBy
类似于SQL语法中的 order by
,例如:
db.collection('table0508').where({
sex: '男'
}).orderBy('age', 'desc').get()
如果有多个排序字段,则需使用多个 orderBy()
函数,例如:
db.collection('table0508').where({
sex: '男'
}).orderBy('age', 'desc').orderBy('name', 'asc').get()
limit和skip
limit
是限制返回的记录数量,例如:
db.collection('table0508').limit(3).get()
skip
是指忽略前面的多少条记录,例如:
db.collection('table0508').skip(4).get()
limit
和 skip
可以一起使用,二者顺序不限,例如:
db.collection('table0508').skip(4).limit(2).get()
field
指定返回结果中记录需返回的字段,例如:
db.collection('table0508').field({
name: true,
sex: true,
age: true
}).get()
注:最后一个字段后面加不加逗号都可以。
注:貌似只能指定true,不能false,否则会报错 Error: InvalidParameterValue.QueryProjection, Query projection entered in the request is illegal. Please check your request, but if the problem persists, contact us. (86bb1074-8631-4319-943e-a669509afd87)
,那不需要的字段,干脆就不要放了。
command
对于逻辑运算(与或非)和比较运算(比如大于小于等于)等,需要用command来做。
云开发控制台的脚本,自带 _
变量。
小程序端:
const _ = db.command
比较运算
eq
:等于neq
:不等于lt
:小于lte
:小于等于gt
:大于gte
:大于等于in
:在指定集合内nin
:不在指定集合内exists
:判断字段是否存在
例如:
db.collection('table0508').where({
age: _.gt(30)
}).get()
db.collection('table0508').where({
name: _.in(['郭靖', '段誉'])
}).get()
db.collection('table0508').where({
sex: _.exists(true)
}).get()
逻辑运算
and
:与or
:或not
:非nor
:既不……,又不……
例如:
db.collection('table0508').where(
_.and([
{
sex: '男',
},
{
age: 25
}
])
).get()
db.collection('table0508').where(
_.or([
{
sex: '女',
},
{
age: 40
}
])
).get()
db.collection('table0508').where({
name: _.not(
_.eq('小龙女')
)
}).get()
报错: RuntimeError: cannot read property 'not'
。
查看SDK文档( https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/database/command/Command.not.html
),里面说 支持端:小程序 2.8.3, 云函数 1.2.1, Web
。我在小程序端测试OK,小程序端的版本如下:
不知道云数据库脚本应该如何设置?
db.collection('table0508').where({
name: _.nor([
_.eq('杨过'), _.eq('张无忌')
])
}).get()
同上。
aggregate
云开发控制台的脚本,自带 $
变量。
小程序端:
const $ = db.command.aggregate
直接看例子:
db.collection('table0508').aggregate().group({
_id: '$sex',
avgAge: $.avg('$age')
})
.end()
相当于SQL语句: select sex, avg(age) from t1 group by sex
聚合操作有很多,比较复杂,这里不再赘述,等用到的时候再仔细研究吧。
参考
https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/Cloud.database.html