clientdb.md 88.6 KB
Newer Older
W
wanganxp 已提交
1
## clientDB简介
雪洛's avatar
雪洛 已提交
2

雪洛's avatar
雪洛 已提交
3
> 自`HBuilderX 2.9.5`起支持在客户端直接使用`uniCloud.database()`方式获取数据库引用,即在前端直接操作数据库,这个功能被称为`clientDB`
hbcui1984's avatar
hbcui1984 已提交
4

雪洛's avatar
雪洛 已提交
5
> `HBuilderX 2.9.5`以前的用户如使用过`clientDB`,在升级后请将`clientDB`的前端库和云函数删除,新版已经在前端和云端内置了`clientDB`
雪洛's avatar
雪洛 已提交
6

W
wanganxp 已提交
7
使用`clientDB`的好处:**不用写服务器代码了!**
雪洛's avatar
雪洛 已提交
8

W
wanganxp 已提交
9
1个应用开发的一半的工作量,就此直接省去。
W
wanganxp 已提交
10

W
wanganxp 已提交
11
当然使用`clientDB`需要扭转传统后台开发观念,不再编写服务端代码,直接在前端操作数据库。但是为了数据安全,需要在数据库上配置`DB Schema`
W
wanganxp 已提交
12

W
wanganxp 已提交
13
`DB Schema`中,配置数据操作的权限和字段值域校验规则,阻止前端不恰当的数据读写。详见:[DB Schema](https://uniapp.dcloud.net.cn/uniCloud/schema)
W
wanganxp 已提交
14

W
wanganxp 已提交
15
如果想在数据库操作之前或之后需要在云端执行额外的动作(比如获取文章详情之后阅读量+1),`clientDB`提供了action云函数机制。在HBuilderX项目的`cloudfunctions/uni-clientDB-actions`目录编写上传js,参考:[action](uniCloud/database?id=action)
雪洛's avatar
雪洛 已提交
16 17 18

**注意**

雪洛's avatar
雪洛 已提交
19
- `clientDB`依赖uni-id(`1.1.10+版本`)提供用户身份和权限校验,如果你不了解uni-id,请参考[uni-id文档](https://uniapp.dcloud.net.cn/uniCloud/uni-id)
雪洛's avatar
雪洛 已提交
20
- `clientDB`依赖的uni-id需要在uni-id的config.json内添加uni-id相关配置,通过uni-id的init方法传递的参数不会对clientDB生效
W
wanganxp 已提交
21
- 通常在管理控制台使用`clientDB`,需要获取不同角色用户拥有的权限(在权限规则内使用auth.permission),请先查阅[uni-id 角色权限](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=rbac)
雪洛's avatar
雪洛 已提交
22

W
wanganxp 已提交
23 24 25
## clientDB图解
![](https://static-eefb4127-9f58-4963-a29b-42856d4205ee.bspapp.com/clientdb.jpg)

W
wanganxp 已提交
26
`clientDB`的前端,有两种用法,可以用js API操作云数据库,也可以使用`<unicloud-db>`组件。
雪洛's avatar
雪洛 已提交
27

W
wanganxp 已提交
28
js API可以执行所有数据库操作。`<unicloud-db>`组件是js API的再封装,进一步简化查询等常用数据库操作的代码量。
雪洛's avatar
雪洛 已提交
29

W
wanganxp 已提交
30 31
- 在HBuilderX 3.0+,`<unicloud-db>`组件已经内置,可以直接使用。文档另见:[<unicloud-db>组件](/uniCloud/unicloud-db)
- 在HBuilderX 3.0以前的版本,使用该组件需要在插件市场单独引用`<uni-clientDB>插件`,另见:[https://ext.dcloud.net.cn/plugin?id=3256](https://ext.dcloud.net.cn/plugin?id=3256)
W
wanganxp 已提交
32

W
wanganxp 已提交
33
以下文章重点介绍`clientDB`的js API。至于组件的用法,另见[文档](/uniCloud/unicloud-db)
雪洛's avatar
雪洛 已提交
34

W
wanganxp 已提交
35 36 37 38 39 40 41 42 43
## clientDB前端API@jssdk

`clientDB`的客户端部分主要负责提供API,允许前端编写数据库操作指令,以及处理一些客户端不太方便表示的字段,比如用户ID(详情看下面语法扩展部分)

`clientDB`支持传统的nosql查询语法,并新增了`jql`查询语法。`jql`是一种更易用的查询语法。

**传统nosql查询语法示例**

这段示例代码,在一个前端页面,直接查询了云数据库的`list`表,并且指定了`name`字段值为`hello-uni-app`的查询条件,then里的res即为返回的查询结果。
雪洛's avatar
雪洛 已提交
44 45 46

```js
// 获取db引用
W
wanganxp 已提交
47
const db = uniCloud.database() //代码块为cdb
雪洛's avatar
雪洛 已提交
48 49 50
// 使用uni-clientDB
db.collection('list')
  .where({
W
wanganxp 已提交
51
    name: "hello-uni-app" //传统MongoDB写法,不是jql写法。实际开发中推荐使用jql写法
雪洛's avatar
雪洛 已提交
52 53 54 55
  }).get()
  .then((res)=>{
    // res 为数据库查询结果
  }).catch((err)=>{
W
wanganxp 已提交
56 57
    console.log(err.code); // 打印错误码
		console.log(err.message); // 打印错误内容
雪洛's avatar
雪洛 已提交
58 59 60 61 62
  })
```

**使用说明**

雪洛's avatar
雪洛 已提交
63
前端操作数据库的语法与云函数一致,但有以下限制(使用jql语法时也一样):
雪洛's avatar
雪洛 已提交
64 65

- 上传时会对query进行序列化,除Date类型、RegExp之外的所有不可序列化的参数类型均不支持(例如:undefined)
W
wanganxp 已提交
66
- 为方便控制权限,禁止前端使用set方法,一般情况下也不需要前端使用set
雪洛's avatar
雪洛 已提交
67 68 69
- 更新数据库时不可使用更新操作符`db.command.inc`
- 更新数据时键值不可使用`{'a.b.c': 1}`的形式,需要写成`{a:{b:{c:1}}}`形式(后续会对此进行优化)

W
wanganxp 已提交
70
### err返回值说明@returnvalue
雪洛's avatar
雪洛 已提交
71

W
wanganxp 已提交
72
`clientDB`如果云端返回错误,err的返回值形式如下,
雪洛's avatar
雪洛 已提交
73 74 75 76 77 78 79 80 81

```js
{
  code: "", // 错误码
  message: "" // 错误信息
  ... // 数据库指令执行结果
}
```

W
wanganxp 已提交
82
**err.code错误码列表**
雪洛's avatar
雪洛 已提交
83 84 85 86 87 88 89

|错误码													|描述																		|
|:-:														|:-:																		|
|TOKEN_INVALID_INVALID_CLIENTID	|token校验未通过(设备特征校验未通过)	|
|TOKEN_INVALID									|token校验未通过(云端已不包含此token)	|
|TOKEN_INVALID_TOKEN_EXPIRED		|token校验未通过(token已过期)					|
|TOKEN_INVALID_WRONG_TOKEN			|token校验未通过(token校验未通过)			|
雪洛's avatar
雪洛 已提交
90
|TOKEN_INVALID_ANONYMOUS_USER   |token校验未通过(当前用户为匿名用户)		|
雪洛's avatar
雪洛 已提交
91
|SYNTAX_ERROR										|语法错误																|
雪洛's avatar
雪洛 已提交
92 93
|PERMISSION_ERROR								|权限校验未通过													|
|VALIDATION_ERROR								|数据格式未通过													|
雪洛's avatar
雪洛 已提交
94
|DUPLICATE_KEY									|索引冲突																|
雪洛's avatar
雪洛 已提交
95 96
|SYSTEM_ERROR										|系统错误																|

W
wanganxp 已提交
97 98 99
如需自定义返回的err对象,可以在clientDB中挂一个[action云函数](uniCloud/database?id=action),在action云函数的`after`内用js修改返回结果,传入`after`内的result不带code和message。


雪洛's avatar
雪洛 已提交
100
### 云端环境变量@variable
雪洛's avatar
雪洛 已提交
101

W
wanganxp 已提交
102
`clientDB`目前内置了3个变量可以供客户端使用,客户端并非直接获得这三个变量的值,而是需要传递给云端,云数据库在数据入库时会把变量替换为实际值。
雪洛's avatar
雪洛 已提交
103

雪洛's avatar
雪洛 已提交
104 105 106 107 108
|参数名					|说明								|
|:-:						|:-:								|
|db.env.uid			|用户uid,依赖uni-id|
|db.env.now			|服务器时间戳				|
|db.env.clientIP|当前客户端IP				|
雪洛's avatar
雪洛 已提交
109 110 111

使用这些变量,将可以避免过去在服务端代码中写代码获取用户uid、时间和客户端ip的麻烦。

雪洛's avatar
雪洛 已提交
112 113 114
```js
const db = uniCloud.database()
let res = await db.collection('table').where({
W
wanganxp 已提交
115
  user_id: db.env.uid // 查询当前用户的数据。虽然代码编写在客户端,但环境变量会在云端运算
雪洛's avatar
雪洛 已提交
116 117 118
}).get()
```

雪洛's avatar
雪洛 已提交
119
`HBuilderX 3.1.0`起,上述环境变量用法有调整(旧版依然兼容,但是推荐使用新用法),以下示例为在新版HBuilderX下如何获取上述变量
雪洛's avatar
雪洛 已提交
120 121 122 123 124 125 126 127 128 129 130

```js
const db = uniCloud.database()
const uid = db.getCloudEnv('$cloudEnv_uid')
const now = db.getCloudEnv('$cloudEnv_now')
const clientIP = db.getCloudEnv('$cloudEnv_clientIP')
```

使用JQL查询语法时如需使用上述变量可以使用如下写法

```js
雪洛's avatar
雪洛 已提交
131
// HBuilderX 3.1.0及以上版本
雪洛's avatar
雪洛 已提交
132 133 134 135 136
const db = uniCloud.database()
const res = await db.collection()
.where('user_id == $cloudEnv_uid')
.get()

雪洛's avatar
雪洛 已提交
137
// HBuilderX 3.1.0以下版本
雪洛's avatar
雪洛 已提交
138 139 140 141 142 143
const db = uniCloud.database()
const res = await db.collection()
.where('user_id == $env.uid')  // $env.now、$env.clientIP
.get()
```

雪洛's avatar
雪洛 已提交
144
### JQL查询语法@jsquery
W
wanganxp 已提交
145 146 147

`jql`,全称javascript query language,是一种js方式操作数据库的语法规范。

W
wanganxp 已提交
148
`jql`大幅降低了js工程师操作数据库的难度、大幅缩短开发代码量。并利用json数据库的嵌套特点,极大的简化了联表查询和树查询的复杂度。
W
wanganxp 已提交
149

W
wanganxp 已提交
150
#### jql的诞生背景
W
wanganxp 已提交
151 152

传统的数据库查询,有sql和nosql两种查询语法。
雪洛's avatar
雪洛 已提交
153

W
wanganxp 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
- sql是一种字符串表达式,写法形如:

```
select * from table1 where field1="123"
```

- nosql是js方法+json方式的参数,写法形如:

```js
const db = uniCloud.database()
let res = await db.collection('table').where({
  field1: '123'
}).get()
```

sql写法,对js工程师而言有学习成本,而且无法处理非关系型的MongoDB数据库,以及sql的联表查询inner join、left join也并不易于学习。

W
wanganxp 已提交
171
而nosql的写法,实在过于复杂。比如如下3个例子:
W
wanganxp 已提交
172

雪洛's avatar
雪洛 已提交
173
1. 运算符需要转码,`>`需要使用`gt`方法、`==`需要使用`eq`方法
W
wanganxp 已提交
174

雪洛's avatar
雪洛 已提交
175
  比如一个简单的查询,取field1>0,则需要如下复杂写法
W
wanganxp 已提交
176

雪洛's avatar
雪洛 已提交
177 178 179 180 181 182 183
  ```js
  const db = uniCloud.database()
  const dbCmd = db.command
  let res = await db.collection('table1').where({
    field1: dbCmd.gt(0)
  }).get()
  ```
W
wanganxp 已提交
184

雪洛's avatar
雪洛 已提交
185 186 187 188 189
  如果要表达`或`关系,需要用`or`方法,写法更复杂

  ```js
  field1:dbCmd.gt(4000).or(dbCmd.gt(6000).and(dbCmd.lt(8000)))
  ```
W
wanganxp 已提交
190 191

2. nosql的联表查询写法,比sql还复杂
雪洛's avatar
雪洛 已提交
192

雪洛's avatar
雪洛 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
  sql的inner join、left join已经够乱了,而nosql的代码无论写法还是可读性,都更“令人发指”。比如这个联表查询:

  ```js
  const db = uniCloud.database()
  const dbCmd = db.command
  const $ = dbCmd.aggregate
  let res = await db.collection('orders').aggregate()
  .lookup({
    from: 'books',
    let: {
      order_book: '$book',
      order_quantity: '$quantity'
    },
    pipeline: $.pipeline()
      .match(dbCmd.expr($.and([
        $.eq(['$title', '$$order_book']),
        $.gte(['$stock', '$$order_quantity'])
      ])))
      .project({
        _id: 0,
        title: 1,
        author: 1,
        stock: 1
      })
      .done(),
    as: 'bookList',
  })
  .end()
  ```
W
wanganxp 已提交
222

W
wanganxp 已提交
223 224
3. 列表分页写法复杂

雪洛's avatar
雪洛 已提交
225
  需要使用skip,处理offset
W
wanganxp 已提交
226 227 228



W
wanganxp 已提交
229 230 231 232 233
这些问题竖起一堵墙,让后端开发难度加大,成为一个“专业领域”。但其实这堵墙是完全可以推倒的。

`jql`将解决这些问题,让js工程师没有难操作的数据。

具体看以下示例
雪洛's avatar
雪洛 已提交
234

雪洛's avatar
雪洛 已提交
235 236 237 238 239 240 241 242 243 244 245 246 247 248
  ```js
  const db = uniCloud.database()

  // 上面的示例中的where条件可以使用以下写法
  db.collection('list')
    .where('name == "hello-uni-app"')
    .get()
    .then((res)=>{
      // res 为数据库查询结果
    }).catch((err)=>{
      // err.message 错误信息
      // err.code 错误码
    })
  ```
雪洛's avatar
雪洛 已提交
249

W
wanganxp 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263
除了js写法,uniCloud还提供了`<uni-clientdb>`组件,可以在前端页面中直接查询云端数据并绑定到界面上。[详情](https://ext.dcloud.net.cn/plugin?id=3256)
比如下面的代码,list表中查询到符合条件的记录可以直接绑定渲染到界面上

```html
<uni-clientdb v-slot:default="{loading, data, error, options}" :options="options"
 collection="list" where='name == "hello-uni-app"' :getone="true">
	<view v-if="error" class="error">{{error}}</view>
	<view v-else>
		{{item.name}}
	</view>
	<view class="loading" v-if="loading">加载中...</view>
</uni-clientdb>
```

雪洛's avatar
雪洛 已提交
264
**jql条件语句内变量**
W
wanganxp 已提交
265

雪洛's avatar
雪洛 已提交
266
以下变量同[前端环境变量](uniCloud/database.md?id=variable)
W
wanganxp 已提交
267

雪洛's avatar
雪洛 已提交
268 269 270 271 272
|参数名			|说明				|
|:-:			|:-:				|
|$env.uid		|用户uid,依赖uni-id|
|$env.now		|服务器时间戳		|
|$env.clientIP|当前客户端IP		|
W
wanganxp 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

**jql条件语句的运算符**

|运算符			|说明			|示例								|示例解释(集合查询)																		|
|:-:			|:-:			|:-:								|:-:																					|
|==				|等于			|name == 'abc'						|查询name属性为abc的记录,左侧为数据库字段												|
|!=				|不等于			|name != 'abc'						|查询name属性不为abc的记录,左侧为数据库字段											|
|>				|大于			|age>10								|查询条件的 age 属性大于 10,左侧为数据库字段											|
|>=				|大于等于		|age>=10							|查询条件的 age 属性大于等于 10,左侧为数据库字段										|
|<				|小于			|age<10								|查询条件的 age 属性小于 10,左侧为数据库字段											|
|<=				|小于等于		|age<=10							|查询条件的 age 属性小于等于 10,左侧为数据库字段										|
|in				|存在在数组中	|status in ['a','b']				|查询条件的 status 是['a','b']中的一个,左侧为数据库字段								|
|!				|非				|!(status in ['a','b'])				|查询条件的 status 不是['a','b']中的任何一个											|
|&&				|与				|uid == auth.uid && age > 10		|查询记录uid属性 为 当前用户uid 并且查询条件的 age 属性大于 10							|
|&#124;&#124;	|或				|uid == auth.uid&#124;&#124;age>10	|查询记录uid属性 为 当前用户uid 或者查询条件的 age 属性大于 10							|
|test			|正则校验		|/abc/.test(content)				|查询 content字段内包含 abc 的记录。可用于替代sql中的like。还可以写更多正则实现更复杂的功能	|

这里的test方法比较强大,格式为:`正则规则.test(fieldname)`
雪洛's avatar
雪洛 已提交
291

W
wanganxp 已提交
292 293
具体到这个正则 `/abc/.test(content)`,类似于sql中的`content like '%abc%'`,即查询所有字段content包含abc的数据记录。

雪洛's avatar
雪洛 已提交
294 295
**云函数中node版本为8.9不支持正则断言**

W
wanganxp 已提交
296
**注意编写查询条件时,除test外,均为运算符左侧为数据库字段,右侧为常量**
雪洛's avatar
雪洛 已提交
297

雪洛's avatar
雪洛 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
#### 查询数组字段@querywitharr

如果数据库存在以下记录

```js
{
  "_id": "1",
  "students": ["li","wang"]
}
{
  "_id": "2",
  "students": ["wang","li"]
}
{
  "_id": "3",
  "students": ["zhao","qian"]
}
```

使用jql查询语法时,可以直接使用`student=='wang'`作为查询条件来查询students内包含wang的记录。
雪洛's avatar
雪洛 已提交
318 319 320 321 322 323 324 325 326 327 328

#### 常见正则用法@regexp

**搜索用户输入值**

如果使用[unicloud-db组件](uniCloud/unicloud-db.md)写法如下,使用clientDB jssdk同理

```html
<template>
	<view class="content">
		<input @input="onKeyInput" placeholder="请输入搜索值" />
雪洛's avatar
雪洛 已提交
329
		<unicloud-db v-slot:default="{data, loading, error, options}" collection="goods" :where=`${new RegExp(searchVal, 'i')}.test(name)`>
雪洛's avatar
雪洛 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
			<view v-if="error">{{error.message}}</view>
			<view v-else>
				
			</view>
		</unicloud-db>
	</view>
</template>

<script>
	export default {
		data() {
			return {
        searchVal: ''
      }
		},
		methods: {
      onKeyInput(e){
        // 实际开发中这里应该还有防抖或者节流操作,这里不做演示
        this.searchVal = e.target.value
      }
		}
	}
</script>

<style>
</style>

```

上面的示例中使用了正则修饰符`i`,用于表示忽略大小写,更多修饰符见[MDN 通过标志进行高级搜索](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions#%E9%80%9A%E8%BF%87%E6%A0%87%E5%BF%97%E8%BF%9B%E8%A1%8C%E9%AB%98%E7%BA%A7%E6%90%9C%E7%B4%A2)


W
wanganxp 已提交
362
### JQL联表查询@lookup
W
wanganxp 已提交
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393

`JQL`提供了更简单的联表查询方案。不需要学习join、lookup等复杂方法。

只需在db schema中,将两个表的关联字段建立映射关系,就可以把2个表当做一个虚拟表来直接查询。

比如有2个表,book表,存放书籍商品;order表存放书籍销售订单记录。

book表内有以下数据,title为书名、author为作者:

```js
{
  "_id": "1",
  "title": "西游记",
  "author": "吴承恩"
}
{
  "_id": "2",
  "title": "水浒传",
  "author": "施耐庵"
}
{
  "_id": "3",
  "title": "三国演义",
  "author": "罗贯中"
}
{
  "_id": "4",
  "title": "红楼梦",
  "author": "曹雪芹"
}
```
雪洛's avatar
雪洛 已提交
394

雪洛's avatar
雪洛 已提交
395
order表内有以下数据,book_id字段为book表的书籍_id,quantity为该订单销售了多少本书:
雪洛's avatar
雪洛 已提交
396

W
wanganxp 已提交
397 398
```js
{
雪洛's avatar
雪洛 已提交
399
  "book_id": "1",
W
wanganxp 已提交
400 401 402
  "quantity": 111
}
{
雪洛's avatar
雪洛 已提交
403
  "book_id": "2",
W
wanganxp 已提交
404 405 406
  "quantity": 222
}
{
雪洛's avatar
雪洛 已提交
407
  "book_id": "3",
W
wanganxp 已提交
408 409 410
  "quantity": 333
}
{
雪洛's avatar
雪洛 已提交
411
  "book_id": "4",
W
wanganxp 已提交
412 413 414
  "quantity": 444
}
{
雪洛's avatar
雪洛 已提交
415
  "book_id": "3",
W
wanganxp 已提交
416 417 418
  "quantity": 555
}
```
雪洛's avatar
雪洛 已提交
419

W
wanganxp 已提交
420
如果我们要对这2个表联表查询,在订单记录中同时显示书籍名称和作者,那么首先要建立两个表中关联字段`book`的映射关系。
雪洛's avatar
雪洛 已提交
421

雪洛's avatar
雪洛 已提交
422
即,在order表的db schema中,配置字段 book_id 的`foreignKey`,指向 book 表的 _id 字段,如下
雪洛's avatar
雪洛 已提交
423 424 425 426 427 428 429

```json
// order表schema
{
  "bsonType": "object",
  "required": [],
  "permission": {
雪洛's avatar
雪洛 已提交
430
    "read": true
雪洛's avatar
雪洛 已提交
431 432
  },
  "properties": {
雪洛's avatar
雪洛 已提交
433
    "book_id": {
雪洛's avatar
雪洛 已提交
434
      "bsonType": "string",
雪洛's avatar
雪洛 已提交
435
      "foreignKey": "book._id" // 使用foreignKey表示,此字段关联book表的_id。
雪洛's avatar
雪洛 已提交
436 437 438 439 440 441
    },
    "quantity": {
      "bsonType": "int"
    }
  }
}
W
wanganxp 已提交
442
```
雪洛's avatar
雪洛 已提交
443

W
wanganxp 已提交
444 445
book表的db schema也要保持正确
```json
雪洛's avatar
雪洛 已提交
446 447 448 449 450
// book表schema
{
  "bsonType": "object",
  "required": [],
  "permission": {
雪洛's avatar
雪洛 已提交
451
    "read": true
雪洛's avatar
雪洛 已提交
452 453 454 455 456 457 458 459 460 461 462 463
  },
  "properties": {
    "title": {
      "bsonType": "string"
    },
    "author": {
      "bsonType": "string"
    }
  }
}
```

W
wanganxp 已提交
464
schema保存至云端后,即可在前端直接查询。查询表设为order和book这2个表名后,即可自动按照一个合并虚拟表来查询,field、where等设置均按合并虚拟表来设置。
W
wanganxp 已提交
465

雪洛's avatar
雪洛 已提交
466 467 468
```js
// 客户端联表查询
const db = uniCloud.database()
W
wanganxp 已提交
469
db.collection('order,book') // 注意collection方法内需要传入所有用到的表名,用逗号分隔,主表需要放在第一位
雪洛's avatar
雪洛 已提交
470 471
  .where('book_id.title == "三国演义"') // 查询order表内书名为“三国演义”的订单
  .field('book_id{title,author},quantity') // 这里联表查询book表返回book表内的title、book表内的author、order表内的quantity
W
wanganxp 已提交
472 473 474 475 476 477
  .get()
  .then(res => {
    console.log(res);
  }).catch(err => {
    console.error(err)
  })
雪洛's avatar
雪洛 已提交
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
  
// 上面的写法是clientDB的jql语法,如果不使用jql的话,写法会变得很长,大致如下
// 注意clientDB内联表查询需要用拼接子查询的方式(let+pipeline)
const db = uniCloud.database()
const dbCmd = db.command
const $ = dbCmd.aggregate
db.collection('order')
  .aggregate()
  .lookup({
    from: 'book',
    let: {
      book_id: '$book_id'
    },
    pipeline: $.pipeline()
    // 此match方法内的条件会和book表对应的权限规则进行校验,{status: 'OnSell'}会参与校验,整个expr方法转化成一个不与任何条件产生交集的特别表达式。这里如果将dbCmd.and换成dbCmd.or会校验不通过
    .match(dbCmd.expr(
        $.eq(['$_id', '$$book_id'])
      ))
    .done()
    as: 'book'
  })
  .match({
    book: {
      title: '三国演义'
    }
  })
  .end()
雪洛's avatar
雪洛 已提交
505 506 507
```


雪洛's avatar
雪洛 已提交
508
上述查询会返回如下结果,可以看到书籍信息被嵌入到order表的book_id字段下,成为子节点。同时根据where条件设置,只返回书名为三国演义的订单记录。
雪洛's avatar
雪洛 已提交
509 510 511 512 513 514 515

```js
{
	"code": "",
	"message": "",
	"data": [{
		"_id": "b8df3bd65f8f0d06018fdc250a5688bb",
雪洛's avatar
雪洛 已提交
516
		"book_id": [{
雪洛's avatar
雪洛 已提交
517 518 519 520 521 522
			"author": "罗贯中",
			"title": "三国演义"
		}],
		"quantity": 555
	}, {
		"_id": "b8df3bd65f8f0d06018fdc2315af05ec",
雪洛's avatar
雪洛 已提交
523
		"book_id": [{
雪洛's avatar
雪洛 已提交
524 525 526 527 528 529 530 531 532
			"author": "罗贯中",
			"title": "三国演义"
		}],
		"quantity": 333
	}]
}

```

W
wanganxp 已提交
533
关系型数据库做不到这种设计。`jql`充分利用了json文档型数据库的特点,实现了这个简化的联表查询方案。
W
wanganxp 已提交
534 535 536 537 538

不止是2个表,3个、4个表也可以通过这种方式查询。

不止js,`<uni-clientDB>`组件也支持所有`jql`功能,包括联表查询。

雪洛's avatar
雪洛 已提交
539 540 541
**注意**

- field参数字符串内没有冒号,{}为联表查询标志
雪洛's avatar
雪洛 已提交
542
- 联表查询时关联字段会被替换成被关联表的内容,因此不可在where内使用关联字段作为条件。举个例子,在上面的示例,`where({book_id:"1"})`,但是可以使用`where({'book_id._id':"1"})`
雪洛's avatar
雪洛 已提交
543
- 上述示例中如果order表的`book_id`字段是数组形式存放多个book_id,也跟上述写法一致,clientDB会自动根据字段类型进行联表查询
雪洛's avatar
雪洛 已提交
544

雪洛's avatar
雪洛 已提交
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
### 查询条件@where

jql对查询条件进行了简化,开发者可以使用`where('a==1||b==2')`来表示字段`a等于1或字段b等于2`。如果不适用jql语法,上述条件需要写成下面这种形式

```js
const db = uniCloud.database()
const dbCmd = db.command
const res = await db.collection('test')
  .where(
    dbCmd.or({
      a:1
    },{
      b:2
    })
  )
  .get()
```

两种用法性能上并没有太大差距,可以视场景选择合适的写法。

jql支持两种类型的查询条件,以下内容有助于理解两种的区别,实际书写的时候无需过于关心是简单查询条件还是复杂查询条件,**JQL会自动进行选择**

where内还支持使用云端环境变量,详情参考:[云端环境变量](uniCloud/clientdb.md?id=variable)

#### 简单查询条件

简单查询条件包括以下几种,对应着db.command下的各种[操作符](https://uniapp.dcloud.net.cn/uniCloud/cf-database?id=dbcmd)以及不使用操作符的查询如`where({a:1})`

|运算符				|说明			|
|---					|---			|
|>						|大于			|
|<						|小于			|
|==						|等于			|
|>=						|大于等于	|
|<=						|小于等于	|
|!=						|大于			|
|&&						|与				|
|&#124;&#124;	|或				|
|!						|非				|
|test					|正则			|

简单查询条件内要求二元运算符两侧不可均为数据库内的字段

上述写法的查询语句可以在权限校验阶段与schema内配置的permission进行一次对比校验,如果校验通过则不会再查库进行权限校验。

#### 复杂查询条件

> HBuilderX 3.1.0起支持

复杂查询对应着[聚合操作符](uniCloud/clientdb.md?id=aggregate-operator)。需要注意的是,与云函数内使用聚合操作符不同jql内对聚合操作符的用法进行了简化。

例:数据表test内有以下数据

```js
{
  "_id": "1",
  "name": "n1",
  "chinese": 60, // 语文
  "math": 60 // 数学
}
{
  "_id": "2",
  "name": "n2",
  "chinese": 60,
  "math": 70
}
{
  "_id": "3",
  "name": "n3",
  "chinese": 100,
  "math": 90
}
```

使用如下写法可以筛选语文数学总分大于150的数据

```js
const db = uniCloud.database()
const res = await db.collection('test')
.where('add(chinese,math) > 150')
.get()

// 返回结果如下
res = {
  result: {
    data: [{
      "_id": "3",
      "name": "n3",
      "chinese": 100,
      "math": 90
    }]
  }
}
```

另外与简单查询条件相比,复杂查询条件可以比较数据库内的两个字段,简单查询条件则要求二元运算符两侧不可均为数据库内的字段,**JQL会自动判断要使用简单查询还是复杂查询条件**

例:仍以上面的数据为例,以下查询语句可以查询数学得分比语文高的记录

```js
const db = uniCloud.database()
const res = await db.collection('test')
.where('math > chinese')
.get()

// 返回结果如下
res = {
  result: {
    data: [{
      "_id": "2",
      "name": "n2",
      "chinese": 60,
      "math": 70
    }]
  }
}
```

**注意**

- 使用了复杂查询条件时不可以使用正则查询
- 不同于简单查询条件,复杂查询条件必然会进行查库校验权限

W
wanganxp 已提交
668 669
### 查询列表分页

雪洛's avatar
雪洛 已提交
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
可以通过skip+limit来进行分页查询

```js
const db = uniCloud.database()
db.collection('book')
  .where('status == "onsale"')
  .skip(20) // 跳过前20条
  .limit(20) // 获取20条
  .get()
  
// 上述用法对应的分页条件为:每页20条取第2页
```

**注意**

- limit不设置的情况下默认返回100条数据;设置limit有最大值,腾讯云限制为最大1000条,阿里云限制为最大500条。

`<unicloud-db>`组件提供了更简单的分页方法,包括两种模式:
W
wanganxp 已提交
688 689 690 691

1. 滚动到底加载下一页
2. 点击页码按钮切换不同页

雪洛's avatar
雪洛 已提交
692
详见:[https://uniapp.dcloud.net.cn/uniCloud/unicloud-db?id=page](https://uniapp.dcloud.net.cn/uniCloud/unicloud-db?id=page)
W
wanganxp 已提交
693

雪洛's avatar
雪洛 已提交
694 695 696 697 698

### 指定返回字段@field

查询时可以使用field方法指定返回字段,在`<uni-clientDB>`组件中也支持field属性。不使用field方法时会返回所有字段

雪洛's avatar
雪洛 已提交
699
只有使用传统MongoDB的写法{ '_id': false }明确指定不要返回_id,否则_id字段一定会返回。
雪洛's avatar
雪洛 已提交
700

雪洛's avatar
雪洛 已提交
701 702
### 别名@alias

雪洛's avatar
雪洛 已提交
703 704 705
`2020-11-20`起clientDB jql写法支持字段别名,主要用于在前端需要的字段名和数据库字段名称不一致的情况下对字段进行重命名。

用法形如:`author as book_author`,意思是将数据库的author字段重命名为book_author。
雪洛's avatar
雪洛 已提交
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723

仍以上面的order表和book表为例

```js
// 客户端联表查询
const db = uniCloud.database()
db.collection('order,book')
  .where('book_id.title == "三国演义"')
  .field('book_id{title as book_title,author as book_author},quantity as order_quantity') // 这里联表查询book表返回book表内的title、book表内的author、order表内的quantity,并将title重命名为book_title,author重命名为book_author,quantity重命名为order_quantity
  .orderBy('order_quantity desc') // 按照order_quantity降序排列
  .get()
  .then(res => {
    console.log(res);
  }).catch(err => {
    console.error(err)
  })
```

雪洛's avatar
雪洛 已提交
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
上述请求返回的res如下

```js
{
	"code": "",
	"message": "",
	"data": [{
		"_id": "b8df3bd65f8f0d06018fdc250a5688bb",
		"book_id": [{
			"book_author": "罗贯中",
			"book_title": "三国演义"
		}],
		"order_quantity": 555
	}, {
		"_id": "b8df3bd65f8f0d06018fdc2315af05ec",
		"book_id": [{
			"book_author": "罗贯中",
			"book_title": "三国演义"
		}],
		"order_quantity": 333
	}]
}
```

雪洛's avatar
雪洛 已提交
748 749
**注意**

雪洛's avatar
雪洛 已提交
750
- 上面的查询指令中,上一阶段处理结果输出到下一阶段,上面的例子中表现为where中使用的是原名,orderBy中使用的是别名
雪洛's avatar
雪洛 已提交
751
- 目前不支持对联表查询的关联字段使用别名,即上述示例中的book_id不可设置别名
雪洛's avatar
雪洛 已提交
752

雪洛's avatar
雪洛 已提交
753
### 对字段操作后返回@operator
雪洛's avatar
雪洛 已提交
754

雪洛's avatar
雪洛 已提交
755
`HBuilderX 3.1.0`起,clientDB支持对字段进行一定的操作之后再返回,详细可用的方法列表请参考:[聚合操作符](uniCloud/clientdb.md?id=aggregate-operator)
雪洛's avatar
雪洛 已提交
756

雪洛's avatar
雪洛 已提交
757 758
> 需要注意的是,为方便书写,clientDB内将聚合操作符的用法进行了简化(相对于云函数内使用聚合操作符而言)。用法请参考上述链接

雪洛's avatar
雪洛 已提交
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
例:数据表class内有以下数据

```js
{
  "_id": "1",
  "grade": 6,
  "class": "A"
}
{
  "_id": "1",
  "grade": 2,
  "class": "A"
}
```

如下写法可以由grade计算得到一个isTopGrade来表示是否为最高年级

```js
const res = await db.collection('class')
雪洛's avatar
雪洛 已提交
778
.field('class,eq(grade,6) as isTopGrade')
雪洛's avatar
雪洛 已提交
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
.get()
```

返回结果如下

```js
{
  "_id": "1",
  "class": "A",
  "isTopGrade": true
}
{
  "_id": "1",
  "class": "A",
  "isTopGrade": false
}
```

**注意**

雪洛's avatar
雪洛 已提交
799
- 如果要访问数组的某一项请使用arrayElemAt操作符,形如:`arrayElemAt(arr,1)`
雪洛's avatar
雪洛 已提交
800 801
- 在进行权限校验时,会计算field内访问的所有字段计算权限。上面的例子中会使用表的read权限和grade、class字段的权限,来进行权限校验。

W
wanganxp 已提交
802
### 排序orderBy@orderby
雪洛's avatar
雪洛 已提交
803

W
wanganxp 已提交
804 805
传统的MongoDB的排序参数是json格式,jql支持类sql的字符串格式,书写更为简单。

雪洛's avatar
雪洛 已提交
806 807
sort方法和orderBy方法内可以传入一个字符串来指定排序规则。

W
wanganxp 已提交
808 809 810 811 812
orderBy允许进行多个字段排序,以逗号分隔。每个字段可以指定 asc(升序)、desc(降序)。

写在前面的排序字段优先级高于后面。

示例如下:
雪洛's avatar
雪洛 已提交
813 814

```js
W
wanganxp 已提交
815
orderBy('quantity asc, create_date desc') //按照quantity字段升序排序,quantity相同时按照create_date降序排序
雪洛's avatar
雪洛 已提交
816
// asc可以省略,上述代码和以下写法效果一致
雪洛's avatar
雪洛 已提交
817
orderBy('quantity, create_date desc')
雪洛's avatar
雪洛 已提交
818

W
wanganxp 已提交
819
// 注意不要写错成全角逗号
雪洛's avatar
雪洛 已提交
820 821
```

W
wanganxp 已提交
822
以上面的order表数据为例:
雪洛's avatar
雪洛 已提交
823

W
wanganxp 已提交
824
```js
雪洛's avatar
雪洛 已提交
825
const db = uniCloud.database()
W
wanganxp 已提交
826 827
  db.collection('order')
    .orderBy('quantity asc, create_date desc') // 按照quantity字段升序排序,quantity相同时按照create_date降序排序
雪洛's avatar
雪洛 已提交
828 829 830 831 832 833
    .get()
    .then(res => {
      console.log(res);
    }).catch(err => {
      console.error(err)
    })
雪洛's avatar
雪洛 已提交
834 835 836 837 838 839 840 841 842 843 844 845
    
// 上述写法等价于
const db = uniCloud.database()
  db.collection('order')
    .orderBy('quantity','asc')
    .orderBy('create_date','desc')
    .get()
    .then(res => {
      console.log(res);
    }).catch(err => {
      console.error(err)
    })
雪洛's avatar
雪洛 已提交
846 847
```

W
wanganxp 已提交
848
### 查询结果返回总数getcount@getcount
雪洛's avatar
雪洛 已提交
849

W
wanganxp 已提交
850
使用`clientDB`时可以在get方法内传入`getCount:true`来同时返回总数
雪洛's avatar
雪洛 已提交
851 852 853 854

```js
// 这以上面的order表数据为例
const db = uniCloud.database()
W
wanganxp 已提交
855
  db.collection('order')
雪洛's avatar
雪洛 已提交
856 857 858 859 860 861 862 863
    .get({
      getCount:true
    })
    .then(res => {
      console.log(res);
    }).catch(err => {
      console.error(err)
    })
雪洛's avatar
雪洛 已提交
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
    
// 如果不使用getCount,需要再调用一次count方法来返回总数
const db = uniCloud.database()
  db.collection('order')
    .get()
    .then(res => {
      console.log(res);
    }).catch(err => {
      console.error(err)
    })
  db.collection('order')
    .count()
    .then(res => {
      console.log(res);
    }).catch(err => {
      console.error(err)
    })
雪洛's avatar
雪洛 已提交
881 882 883 884 885 886 887 888 889 890 891 892 893
```

返回结果为

```js
{
	"code": "",
	"message": "",
	"data": [{
		"_id": "b8df3bd65f8f0d06018fdc250a5688bb",
		"book": "3",
		"quantity": 555
	}],
雪洛's avatar
雪洛 已提交
894
	"count": 5
雪洛's avatar
雪洛 已提交
895 896 897
}
```

W
wanganxp 已提交
898

雪洛's avatar
雪洛 已提交
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
### 查询结果时返回单条记录getone@getone

使用`clientDB`时可以在get方法内传入`getOne:true`来返回一条数据

```js
// 这以上面的book表数据为例
const db = uniCloud.database()
  db.collection('book')
    .where({
      title: '西游记'
    })
    .get({
      getOne:true
    })
    .then(res => {
      console.log(res);
    }).catch(err => {
      console.error(err)
    })
```

返回结果为

```js
{
	"code": "",
	"message": "",
	"data": {
    "_id": "1",
    "title": "西游记",
    "author": "吴承恩"
  }
}
```
W
wanganxp 已提交
933

W
wanganxp 已提交
934
### 查询树形数据gettree@gettree
雪洛's avatar
雪洛 已提交
935

936
HBuilderX 3.0.3+起,clientDB支持在get方法内传入getTree参数查询树状结构数据。(HBuilderX 3.0.5+ unicloud-db组件开始支持,之前版本只能通过js方式使用)
雪洛's avatar
雪洛 已提交
937

W
wanganxp 已提交
938 939 940 941 942 943 944 945 946 947
树形数据,在数据库里一般不会按照tree的层次来存储,因为按tree结构通过json对象的方式存储不同层级的数据,不利于对tree上的某个节点单独做增删改查。

一般存储树形数据,tree上的每个节点都是一条单独的数据表记录,然后通过类似parent_id来表达父子关系。

如部门的数据表,里面有2条数据,一条数据记录是“总部”,`parent_id`为空;另一条数据记录“一级部门A”,`parent_id`为总部的`_id`
```json
{
    "_id": "5fe77207974b6900018c6c9c",
    "name": "总部",
    "parent_id": "",
雪洛's avatar
雪洛 已提交
948
    "status": 0
W
wanganxp 已提交
949 950 951 952 953 954 955
}
```
```json
{
    "_id": "5fe77232974b6900018c6cb1",
    "name": "一级部门A",
    "parent_id": "5fe77207974b6900018c6c9c",
雪洛's avatar
雪洛 已提交
956
    "status": 0
W
wanganxp 已提交
957
}
雪洛's avatar
雪洛 已提交
958 959
```

W
wanganxp 已提交
960
虽然存储格式是分条记录的,但查询反馈到前端的数据仍然需要是树形的。这种转换在过去比较复杂。
雪洛's avatar
雪洛 已提交
961

W
wanganxp 已提交
962 963 964 965 966
clientDB提供了一种简单、优雅的方案,在DB Schema里配置parentKey来表达父子关系,然后查询时声明使用Tree查询,就可以直接查出树形数据。

department部门表的schema中,将字段`parent_id`的"parentKey"设为"_id",即指定了数据之间的父子关系,如下:

```json
雪洛's avatar
雪洛 已提交
967 968
{
  "bsonType": "object",
W
wanganxp 已提交
969
  "required": ["name"],
雪洛's avatar
雪洛 已提交
970
  "properties": {
雪洛's avatar
雪洛 已提交
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
    "_id": {
      "description": "ID,系统自动生成"
    },
      "name": {
      "bsonType": "string",
      "description": "名称"
    },
    "parent_id": {
      "bsonType": "string",
      "description": "父id",
      "parentKey": "_id", // 指定父子关系为:如果数据库记录A的_id和数据库记录B的parent_id相等,则A是B的父级。
    },
    "status": {
      "bsonType": "int",
      "description": "部门状态,0-正常、1-禁用"
    }
雪洛's avatar
雪洛 已提交
987 988 989 990
  }
}
```

W
wanganxp 已提交
991
parentKey字段将数据表不同记录的父子关系描述了出来。查询就可以直接写了。
雪洛's avatar
雪洛 已提交
992

W
wanganxp 已提交
993 994 995 996 997 998 999
注意一个表内只能有一个父子关系,即一个表的schema里只能配置一份parentKey。

schema里描述好后,查询就变的特别简单。

查询树形数据,分为 查询所有子节点 和 查询父级路径 这2种需求。

#### 查询所有子节点
雪洛's avatar
雪洛 已提交
1000

W
wanganxp 已提交
1001
指定符合条件的记录,然后查询它的所有子节点,并且可以指定层级,返回的结果是以符合条件的记录为一级节点的所有子节点数据,并以树形方式嵌套呈现。
雪洛's avatar
雪洛 已提交
1002

W
wanganxp 已提交
1003
只需要在clientDB的get方法中增加`getTree`参数,如下
雪洛's avatar
雪洛 已提交
1004
```js
W
wanganxp 已提交
1005
// get方法示例
雪洛's avatar
雪洛 已提交
1006 1007
get({
  getTree: {
W
wanganxp 已提交
1008 1009
    limitLevel: 10, // 最大查询层级(不包含当前层级),可以省略默认10级,最大15,最小1
    startWith: "parent_code==''"  // 第一层级条件,此初始条件可以省略,不传startWith时默认从最顶级开始查询
雪洛's avatar
雪洛 已提交
1010 1011
  }
})
W
wanganxp 已提交
1012
```
雪洛's avatar
雪洛 已提交
1013

W
wanganxp 已提交
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
完整的代码如下:
```js
db.collection("department").get({
		getTree: {}
	})
	.then((res) => {
		const resdata = res.result.data
		console.log("resdata", resdata);
	}).catch((err) => {
		uni.showModal({
			content: err.message || '请求服务失败',
			showCancel: false
		})
	}).finally(() => {
		
	})
雪洛's avatar
雪洛 已提交
1030 1031
```

W
wanganxp 已提交
1032 1033 1034 1035 1036 1037
查询的结果如下:
```json
"data": [{
	"_id": "5fe77207974b6900018c6c9c",
	"name": "总部",
	"parent_id": "",
雪洛's avatar
雪洛 已提交
1038
	"status": 0,
W
wanganxp 已提交
1039 1040 1041 1042
	"children": [{
		"_id": "5fe77232974b6900018c6cb1",
		"name": "一级部门A",
		"parent_id": "5fe77207974b6900018c6c9c",
雪洛's avatar
雪洛 已提交
1043
		"status": 0,
W
wanganxp 已提交
1044 1045 1046 1047
		"children": []
	}]
}]
```
雪洛's avatar
雪洛 已提交
1048

W
wanganxp 已提交
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
可以看出,每个子节点,被嵌套在父节点的"children"下,这个"children"是一个固定的格式。

如果不指定getTree的参数,会把department表的所有数据都查出来,从总部开始到10级部门,以树形结构提供给客户端。

如果有多个总部,即多行记录的`parent_id`为空,则多个总部会分别作为一级节点,把它们下面的所有children一级一级拉出来。如下:

```json
"data": [
	{
		"_id": "5fe77207974b6900018c6c9c",
		"name": "总部",
		"parent_id": "",
雪洛's avatar
雪洛 已提交
1061
    "status": 0,
W
wanganxp 已提交
1062 1063 1064 1065
		"children": [{
				"_id": "5fe77232974b6900018c6cb1",
				"name": "一级部门A",
				"parent_id": "5fe77207974b6900018c6c9c",
雪洛's avatar
雪洛 已提交
1066
				"status": 0,
W
wanganxp 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
				"children": []
		}]
	},
	{
		"_id": "5fe778a10431ca0001c1e2f8",
		"name": "总部2",
		"parent_id": "",
		"children": [{
				"_id": "5fe778e064635100013efbc2",
				"name": "总部2的一级部门B",
				"parent_id": "5fe778a10431ca0001c1e2f8",
				"children": []
		}]
	}
]
雪洛's avatar
雪洛 已提交
1082 1083
```

W
wanganxp 已提交
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096

如果觉得返回的`parent_id`字段多余,也可以指定`.field("_id,name")`,过滤掉该字段。

**getTree的参数limitLevel的说明**

limitLevel表示查询返回的树的最大层级。超过设定层级的节点不会返回。

- limitLevel的默认值为10。
- limitLevel的合法值域为1-15之间(包含1、15)。如果数据实际层级超过15层,请分层懒加载查询。
- limitLevel为1,表示向下查一级子节点。假如数据库中有2级、3级部门,如果设limitLevel为1,且查询的是“总部”,那么返回数据包含“总部”和其下的一级部门。

**getTree的参数startWith的说明**

雪洛's avatar
雪洛 已提交
1097
如果只需要查“总部”的子部门,不需要“总部2”,可以在startWith里指定(`getTree: {"startWith":"name=='总部'"}`)。
W
wanganxp 已提交
1098

雪洛's avatar
雪洛 已提交
1099
使用中请注意startWith和where的区别。where用于描述对所有层级的生效的条件(包括第一层级)。而startWith用于描述从哪个或哪些节点开始查询树。
W
wanganxp 已提交
1100 1101 1102

startWith不填时,默认的条件是 `'parent_id==null||parent_id==""'`,即schema配置parentKey的字段为null(即不存在)或值为空字符串时,这样的节点被默认视为根节点。

雪洛's avatar
雪洛 已提交
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
假设上述部门表内有以下数据

```js
{
    "_id": "1",
    "name": "总部",
    "parent_id": "",
    "status": 0
}
{
    "_id": "11",
    "name": "一级部门A",
    "parent_id": "1",
    "status": 0
}
{
    "_id": "12",
    "name": "一级部门B",
    "parent_id": "1",
    "status": 1
}
```

以下查询语句指定startWith为`_id=="1"`、where条件为`status==0`,查询总部下所有status为0的子节点。

```js
db.collection("department")
  .where('status==0')
  .get({
    getTree: {
      startWith: '_id=="1"'
    }
	})
	.then((res) => {
		const resdata = res.result.data
		console.log("resdata", resdata);
	}).catch((err) => {
		uni.showModal({
			content: err.message || '请求服务失败',
			showCancel: false
		})
	}).finally(() => {
		
	})
```

查询的结果如下:
```json
{
  "data": [{
    "_id": "1",
    "name": "总部",
    "parent_id": "",
    "status": 0,
    "children": [{
      "_id": "11",
      "name": "一级部门A",
      "parent_id": "1",
      "status": 0,
      "children": []
    }]
  }]
}
```

**需要注意的是where内的条件也会对第一级数据生效**,例如将上面的查询改成如下写法

```js
db.collection("department")
  .where('status==1')
  .get({
    getTree: {
      startWith: '_id=="1"'
    }
	})
	.then((res) => {
		const resdata = res.result.data
		console.log("resdata", resdata);
	}).catch((err) => {
		uni.showModal({
			content: err.message || '请求服务失败',
			showCancel: false
		})
	}).finally(() => {
		
	})
```

此时将无法查询到数据,返回结果如下

```js
{
  "data": []
}
```
W
wanganxp 已提交
1198

W
wanganxp 已提交
1199 1200 1201 1202 1203
**示例**

插件市场有一个 家谱 的示例,可以参阅:[https://ext.dcloud.net.cn/plugin?id=3798](https://ext.dcloud.net.cn/plugin?id=3798)


W
wanganxp 已提交
1204 1205 1206 1207 1208 1209
**大数据量的树形数据查询**

如果tree的数据量较大,则不建议一次性把所有的树形数据返回给客户端。建议分层查询,即懒加载。

比如地区选择的场景,全国的省市区数据量很大,一次性查询所有数据返回给客户端非常耗时和耗流量。可以先查省,然后根据选择的省再查市,以此类推。

雪洛's avatar
雪洛 已提交
1210 1211
**注意**

W
wanganxp 已提交
1212
- 暂不支持使用getTree的同时使用联表查询
雪洛's avatar
雪洛 已提交
1213
- 如果使用了where条件会对所有查询的节点生效
雪洛's avatar
雪洛 已提交
1214
- 如果使用了limit设置最大返回数量仅对根节点生效
雪洛's avatar
雪洛 已提交
1215

W
wanganxp 已提交
1216 1217 1218
#### 查询树形结构父节点路径@gettreepath

getTree是查询子节点,而getTreePath,则是查询父节点。
雪洛's avatar
雪洛 已提交
1219

W
wanganxp 已提交
1220
get方法内传入getTreePath参数对包含父子关系的表查询返回树状结构数据某节点路径。
雪洛's avatar
雪洛 已提交
1221 1222 1223 1224 1225

```js
// get方法示例
get({
  getTreePath: {
W
wanganxp 已提交
1226 1227
    limitLevel: 10, // 最大查询层级(不包含当前层级),可以省略默认10级,最大15,最小1
    startWith: 'name=="一级部门A"'  // 末级节点的条件,此初始条件不可以省略
雪洛's avatar
雪洛 已提交
1228 1229 1230 1231
  }
})
```

W
wanganxp 已提交
1232 1233 1234
查询返回的结果为,从“一级部门A”起向上找10级,找到最终节点后,以该节点为根,向下嵌套children,一直到达“一级部门A”。

返回结果只包括“一级部门A”的直系父,其父节点的兄弟节点不会返回。所以每一层数据均只有一个节点。
雪洛's avatar
雪洛 已提交
1235

W
wanganxp 已提交
1236
仍以上面department的表结构和数据为例
雪洛's avatar
雪洛 已提交
1237 1238

```js
W
wanganxp 已提交
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
db.collection("department").get({
		getTreePath: {
			"startWith": "_id=='5fe77232974b6900018c6cb1'"
		}
	})
	.then((res) => {
		const treepath = res.result.data
		console.log("treepath", treepath);
	}).catch((err) => {
		uni.showModal({
			content: err.message || '请求服务失败',
			showCancel: false
		})
	}).finally(() => {
		uni.hideLoading()
		// console.log("finally")
	})
```

查询返回结果

从根节点“总部”开始,返回到“一级部门A”。“总部2”等节点不会返回。

```json
{
  "data": [{
		"_id": "5fe77207974b6900018c6c9c",
		"name": "总部",
		"parent_id": "",
		"children": [{
			"_id": "5fe77232974b6900018c6cb1",
			"name": "一级部门A",
			"parent_id": "5fe77207974b6900018c6c9c"
		}]
	}]
}
```

如果startWith指定的节点没有父节点,则返回自身。

如果startWith匹配的节点不止一个,则以数组的方式,返回每个节点的treepath。

例如“总部”和“总部2”下面都有一个部门的名称叫“销售部”,且`	"startWith": "name=='销售部'"`,则会返回“总部”和“总部2”两条treepath,如下

```json
雪洛's avatar
雪洛 已提交
1284
{
W
wanganxp 已提交
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
	"data": [{
		"_id": "5fe77207974b6900018c6c9c",
		"name": "总部",
		"parent_id": "",
		"children": [{
			"_id": "5fe77232974b6900018c6cb1",
			"name": "销售部",
			"parent_id": "5fe77207974b6900018c6c9c"
		}]
		}, {
		"_id": "5fe778a10431ca0001c1e2f8",
		"name": "总部2",
		"parent_id": "",
		"children": [{
			"_id": "5fe79fea23976b0001508a46",
			"name": "销售部",
			"parent_id": "5fe778a10431ca0001c1e2f8"
		}]
	}]
雪洛's avatar
雪洛 已提交
1304 1305 1306
}
```

W
wanganxp 已提交
1307

雪洛's avatar
雪洛 已提交
1308 1309
**注意**

W
wanganxp 已提交
1310
- 暂不支持使用getTreePath的同时使用其他联表查询语法
雪洛's avatar
雪洛 已提交
1311 1312
- 如果使用了where条件会对所有查询的节点生效

W
wanganxp 已提交
1313
### 分组统计groupby@groupby
雪洛's avatar
雪洛 已提交
1314

W
wanganxp 已提交
1315
> 本地调试支持:`HBuilderX 3.1.0`+;云端支持:2021-1-26日后更新一次云端 DB Schema 生效
雪洛's avatar
雪洛 已提交
1316

W
wanganxp 已提交
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
数据分组统计,即根据某个字段进行分组(groupBy),然后对其他字段分组后的值进行求和、求数量、求均值。

比如统计每日新增用户数,就是按时间进行分组,对每日的用户记录进行count运算。

分组统计有groupBy和groupField。和传统sql略有不同,传统sql没有单独的groupField。

JQL的groupField里不能直接写field字段,只能使用[累计器操作符](uniCloud/clientdb.md?id=accumulator)来处理字段,常见的累积器计算符包括:count(*)、sum(字段名称)、avg(字段名称)。更多累计器操作符[详见](uniCloud/clientdb.md?id=accumulator)

其中count(*)是固定写法。

分组统计的写法如下:

```js
const res = await db.collection('table1').groupBy('field1,field2').groupField('sum(field3) as field4').get()
```

如果额外还在groupBy之前使用了field方法,那么此field的含义并不是最终返回的字段,而是用于对字段预处理,然后将预处理的字段传给groupBy和groupField使用。

与field不同,使用groupField时返回结果不会默认包含`_id`字段。同时开发者也不应该在groupBy和groupField里使用`_id`字段,`_id`是唯一的,没有统一意义。

举例:
如果数据库`score`表为某次比赛统计的分数数据,每条记录为一个学生的分数。学生有所在的年级(grade)、班级(class)、姓名(name)、分数(score)等字段属性。
雪洛's avatar
雪洛 已提交
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384

```js
{
  _id: "1",
  grade: "1",
  class: "A",
  name: "zhao",
  score: 5
}
{
  _id: "2",
  grade: "1",
  class: "A",
  name: "qian",
  score: 15
}
{
  _id: "3",
  grade: "1",
  class: "B",
  name: "li",
  score: 15
}
{
  _id: "4",
  grade: "1",
  class: "B",
  name: "zhou",
  score: 25
}
{
  _id: "5",
  grade: "2",
  class: "A",
  name: "wu",
  score: 25
}
{
  _id: "6",
  grade: "2",
  class: "A",
  name: "zheng",
  score: 35
}
```

W
wanganxp 已提交
1385 1386 1387
接下来我们对这批数据进行分组统计,分别演示如何使用求和、求均值和计数。

#### 求和、求均值示例
雪洛's avatar
雪洛 已提交
1388

雪洛's avatar
雪洛 已提交
1389 1390 1391
groupBy内也可以使用聚合操作符对数据进行处理,为方便书写,clientDB内将聚合操作符的用法进行了简化(相对于云函数内使用聚合操作符而言)。用法请参考:[聚合操作符](uniCloud/clientdb.md?id=aggregate-operator)

groupField内可以使用累计器操作符对分组结果进行统计,所有可用的累计方法请参考[累计器操作符](uniCloud/clientdb.md?id=accumulator),下面以sum(求和)和avg(求均值)为例介绍如何使用
雪洛's avatar
雪洛 已提交
1392 1393 1394 1395 1396 1397

使用sum方法可以对数据进行求和统计。以上述数据为例,如下写法对不同班级进行分数统计

```js
const res = await db.collection('score')
.groupBy('grade,class')
雪洛's avatar
雪洛 已提交
1398
.groupField('sum(score) as totalScore')
雪洛's avatar
雪洛 已提交
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
.get()
```

返回结果如下

```js
{
  data: [{
    grade: "1",
    class: "A",
    totalScore: 20
  },{
    grade: "1",
    class: "B",
    totalScore: 40
  },{
    grade: "2",
    class: "A",
    totalScore: 60
  }]
}
```

W
wanganxp 已提交
1422 1423
1年级A班、1年级B班、2年级A班,3个班级的总分分别是20、40、60。

雪洛's avatar
雪洛 已提交
1424 1425 1426 1427 1428
求均值方法与求和类似,将上面sum方法换成avg方法即可

```js
const res = await db.collection('score')
.groupBy('grade,class')
雪洛's avatar
雪洛 已提交
1429
.groupField('avg(score) as avgScore')
雪洛's avatar
雪洛 已提交
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
.get()
```

返回结果如下

```js
{
  data: [{
    grade: "1",
    class: "A",
    avgScore: 10
  },{
    grade: "1",
    class: "B",
    avgScore: 20
  },{
    grade: "2",
    class: "A",
    avgScore: 30
  }]
}
```


雪洛's avatar
雪洛 已提交
1454
如果额外还在groupBy之前使用了field方法,此field用于决定将哪些数据传给groupBy和groupField使用
雪洛's avatar
雪洛 已提交
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502

例:如果上述数据中score是一个数组

```js
{
  _id: "1",
  grade: "1",
  class: "A",
  name: "zhao",
  score: [1,1,1,1,1]
}
{
  _id: "2",
  grade: "1",
  class: "A",
  name: "qian",
  score: [3,3,3,3,3]
}
{
  _id: "3",
  grade: "1",
  class: "B",
  name: "li",
  score: [3,3,3,3,3]
}
{
  _id: "4",
  grade: "1",
  class: "B",
  name: "zhou",
  score: [5,5,5,5,5]
}
{
  _id: "5",
  grade: "2",
  class: "A",
  name: "wu",
  score: [5,5,5,5,5]
}
{
  _id: "6",
  grade: "2",
  class: "A",
  name: "zheng",
  score: [7,7,7,7,7]
}
```

雪洛's avatar
雪洛 已提交
1503
如下field写法将上面的score数组求和之后传递给groupBy和groupField使用。在field内没出现的字段(比如name),在后面的方法里面不能使用
雪洛's avatar
雪洛 已提交
1504 1505 1506

```js
const res = await db.collection('score')
雪洛's avatar
雪洛 已提交
1507
.field('grade,class,sum(score) as userTotalScore')
雪洛's avatar
雪洛 已提交
1508
.groupBy('grade,class')
雪洛's avatar
雪洛 已提交
1509
.groupField('avg(userTotalScore) as avgScore')
雪洛's avatar
雪洛 已提交
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
.get()
```

返回结果如下

```js
{
  data: [{
    grade: "1",
    class: "A",
    avgScore: 10
  },{
    grade: "1",
    class: "B",
    avgScore: 20
  },{
    grade: "2",
    class: "A",
    avgScore: 30
  }]
}
```


W
wanganxp 已提交
1534
#### 统计数量示例
雪洛's avatar
雪洛 已提交
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564

使用count方法可以对记录数量进行统计。以上述数据为例,如下写法对不同班级统计参赛人数

```js
const res = await db.collection('score')
.groupBy('grade,class')
.groupField('count(*) as totalStudents')
.get()
```

返回结果如下

```js
{
  data: [{
    grade: "1",
    class: "A",
    totalStudents: 2
  },{
    grade: "1",
    class: "B",
    totalStudents: 2
  },{
    grade: "2",
    class: "A",
    totalStudents: 2
  }]
}
```

W
wanganxp 已提交
1565 1566 1567 1568
**注意**

- `count(*)`为固定写法,括号里的*可以省略

W
wanganxp 已提交
1569
#### 按日分组统计示例
雪洛's avatar
雪洛 已提交
1570

W
wanganxp 已提交
1571
按时间段统计是常见的需求,而时间段统计会用到日期运算符。
雪洛's avatar
雪洛 已提交
1572

W
wanganxp 已提交
1573
假设要统计[uni-id-users](https://gitee.com/dcloud/opendb/blob/master/collection/uni-id-users/collection.json)表的每日新增注册用户数量。表内有以下数据:
W
wanganxp 已提交
1574 1575

```json
雪洛's avatar
雪洛 已提交
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
{
  "_id": "1",
  "username": "name1",
  "register_date": 1611367810000 // 2021-01-23 10:10:10
}
{
  "_id": "2",
  "username": "name2",
  "register_date": 1611367810000 // 2021-01-23 10:10:10
}
{
  "_id": "3",
  "username": "name3",
  "register_date": 1611367810000 // 2021-01-23 10:10:10
}
{
  "_id": "4",
  "username": "name4",
  "register_date": 1611281410000 // 2021-01-22 10:10:10
}
{
  "_id": "5",
  "username": "name5",
  "register_date": 1611281410000 // 2021-01-22 10:10:10
}
{
  "_id": "6",
  "username": "name6",
  "register_date": 1611195010000 // 2021-01-21 10:10:10
}
```

W
wanganxp 已提交
1608
由于`register_date`字段是时间戳格式,含有时分秒信息。但统计每日新增注册用户时是需要忽略时分秒的。
雪洛's avatar
雪洛 已提交
1609

W
wanganxp 已提交
1610
1. 首先使用add操作符将`register_date`从时间戳转化为日期类型。
雪洛's avatar
雪洛 已提交
1611

W
wanganxp 已提交
1612
add操作符的用法为`add(值1,值2)``add(new Date(0),register_date)`表示给字段register_date + 0,这个运算没有改变具体的时间,但把`register_date`的格式从时间戳转为了日期类型。
雪洛's avatar
雪洛 已提交
1613

W
wanganxp 已提交
1614 1615 1616 1617 1618
2. 然后使用dateToString将add得到的日期格式化为形如`2021-01-21`的字符串,去掉时分秒。

dateToString操作符的用法为`dateToString(日期对象,格式化字符串,时区)`。具体如下:`dateToString(add(new Date(0),register_date),"%Y-%m-%d","+0800")`

3. 然后根据此字符串进行分组统计,得到每天注册用户量。代码如下:
雪洛's avatar
雪洛 已提交
1619 1620 1621 1622

```js
const res = await db.collection('uni-id-users')
.groupBy('dateToString(add(new Date(0),register_date),"%Y-%m-%d","+0800") as date')
W
wanganxp 已提交
1623
.groupField('count(*) as newusercount')
雪洛's avatar
雪洛 已提交
1624
.get()
W
wanganxp 已提交
1625
```
雪洛's avatar
雪洛 已提交
1626

W
wanganxp 已提交
1627 1628
查询返回结果如下:
```js
雪洛's avatar
雪洛 已提交
1629 1630 1631 1632
res = {
  result: {
    data: [{
      date: '2021-01-23',
W
wanganxp 已提交
1633
      newusercount: 3
雪洛's avatar
雪洛 已提交
1634 1635
    },{
      date: '2021-01-22',
W
wanganxp 已提交
1636
      newusercount: 2
雪洛's avatar
雪洛 已提交
1637 1638
    },{
      date: '2021-01-21',
W
wanganxp 已提交
1639
      newusercount: 1
雪洛's avatar
雪洛 已提交
1640 1641 1642 1643 1644
    }]
  }
}
```

W
wanganxp 已提交
1645
完整聚合操作符列表请参考:[clientDB内可使用的聚合操作符](uniCloud/clientdb.md?id=aggregate-operator)
W
wanganxp 已提交
1646

W
wanganxp 已提交
1647
#### count权限控制
雪洛's avatar
雪洛 已提交
1648

W
wanganxp 已提交
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
在使用普通的累积器操作符,如sum、avg时,权限控制与常规的权限控制并无不同。

但使用count时,可以单独配置表级的count权限。

请不要轻率的把[uni-id-users](https://gitee.com/dcloud/opendb/blob/master/collection/uni-id-users/collection.json)表的count权限设为true,即任何人都可以count。这意味着游客将可以获取到你的用户总数量。

count权限的控制逻辑如下:

- 在不使用field,仅使用groupBy和groupField的情况下,会以groupBy和groupField内访问的所有字段的权限来校验访问是否合法。
- 在额外使用field方法的情况下,会计算field内访问的所有字段计算权限。上面的例子中会使用表的read权限和grade、class、score三个字段的权限,来进行权限校验。
- 在HBuilderX 3.1.0之前,count操作都会使用表级的read权限进行验证。HBuilderX 3.1.0及之后的版本,如果配置了count权限则会使用表级的read+count权限进行校验,两条均满足才可以通过校验
- 如果schema内没有count权限,则只会使用read权限进行校验
- 所有会统计数量的操作均会触发count权限校验
雪洛's avatar
雪洛 已提交
1662

W
wanganxp 已提交
1663
### 数据去重distinct@distinct
雪洛's avatar
雪洛 已提交
1664

W
wanganxp 已提交
1665 1666
通过.distinct()方法,对数据查询结果中重复的记录进行去重。

W
wanganxp 已提交
1667
distinct方法将按照field方法指定的字段进行去重(如果field内未指定`_id`,不会按照`_id`去重)
雪洛's avatar
雪洛 已提交
1668

W
wanganxp 已提交
1669
> 本地调试支持:`HBuilderX 3.1.0`+;云端支持:2021-1-26日后更新一次云端 DB Schema生效
W
wanganxp 已提交
1670 1671 1672 1673 1674 1675 1676

```js
const res = await db.collection('table1')
.field('field1')
.distinct() // 注意distinct方法没有参数
.get()
```
雪洛's avatar
雪洛 已提交
1677 1678 1679

例:如果数据库`score`表为某次比赛统计的分数数据,每条记录为一个学生的分数

W
wanganxp 已提交
1680 1681
`score`表的数据:

雪洛's avatar
雪洛 已提交
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
```js
{
  _id: "1",
  grade: "1",
  class: "A",
  name: "zhao",
  score: 5
}
{
  _id: "2",
  grade: "1",
  class: "A",
  name: "qian",
  score: 15
}
{
  _id: "3",
  grade: "1",
  class: "B",
  name: "li",
  score: 15
}
{
  _id: "4",
  grade: "1",
  class: "B",
  name: "zhou",
  score: 25
}
{
  _id: "5",
  grade: "2",
  class: "A",
  name: "wu",
  score: 25
}
{
  _id: "6",
  grade: "2",
  class: "A",
  name: "zheng",
  score: 35
}
```

以下代码可以按照grade、class两字段去重,获取所有参赛班级

```js
const res = await db.collection('score')
.field('grade,class')
.distinct() // 注意distinct方法没有参数
.get()
```

W
wanganxp 已提交
1736
查询返回结果如下
雪洛's avatar
雪洛 已提交
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754

```js
{
  data: [{
    grade:"1",
    class: "A"
  },{
    grade:"1",
    class: "B"
  },{
    grade:"2",
    class: "A"
  }]
}
```

**注意**

W
wanganxp 已提交
1755
- distinct指对返回结果中完全相同的记录进行去重,重复的记录只保留一条。因为`_id`字段是必然不同的,所以使用distinct时必须同时指定field,且field中不可存在`_id`字段
雪洛's avatar
雪洛 已提交
1756

W
wanganxp 已提交
1757 1758 1759 1760
### 新增数据记录add

获取到db的表对象后,通过`add`方法新增数据记录。

W
wanganxp 已提交
1761
方法:collection.add(data)
W
wanganxp 已提交
1762

W
wanganxp 已提交
1763
**参数说明**
W
wanganxp 已提交
1764

W
wanganxp 已提交
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
| 参数	| 类型					| 必填	|
| ----	| ------				| ----	|
| data	| object &#124; array	| 是	|

data支持一条记录,也支持多条记录一并新增到集合中。

data中不需要包括`_id`字段,数据库会自动维护该字段。

**返回值**

单条插入时

| 参数	| 类型	|  说明										|
| ----	| ------|  ----------------------------------------	|
|id		| String|插入记录的`_id`								|

批量插入时

| 参数		| 类型	|  说明										|
| ----		| ------|  ----------------------------------------	|
| inserted	| Number| 插入成功条数								|
|ids		| Array	|批量插入所有记录的`_id`						|

**示例:**

比如在user表里新增一个叫王五的记录:
W
wanganxp 已提交
1791 1792 1793

```js
const db = uniCloud.database();
W
wanganxp 已提交
1794
db.collection('user').add({name:"王五"})
W
wanganxp 已提交
1795 1796
```

W
wanganxp 已提交
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
也可以批量插入数据并获取返回值

```js
const db = uniCloud.database();
const collection = db.collection('user');
let res = await collection.add([{
  name: '张三'
},{
  name: '李四'
},{
  name: '王五'
}])
```

如果上述代码执行成功,则res的值将包括inserted:3,代表插入3条数据,同时在ids里返回3条记录的`_id`

如果新增记录失败,会抛出异常,以下代码示例为捕获异常:

W
wanganxp 已提交
1815 1816 1817
```js
// 插入1条数据,同时判断成功失败状态
const db = uniCloud.database();
W
wanganxp 已提交
1818 1819
db.collection("user")
	.add({name: '张三'})
W
wanganxp 已提交
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
	.then((res) => {
		uni.showToast({
			title: '新增成功'
		})
	})
	.catch((err) => {
		uni.showModal({
			content: err.message || '新增失败',
			showCancel: false
		})
	})
	.finally(() => {
		
	})
```

**Tips**
W
wanganxp 已提交
1837 1838
- 如果是非admin账户新增数据,需要在数据库中待操作表的`db schema`中要配置permission权限,赋予create为true。
- 云服务商选择阿里云时,若集合表不存在,调用add方法会自动创建集合表,并且不会报错。
W
wanganxp 已提交
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888


### 删除数据记录remove
获取到db的表对象,然后指定要删除的记录,通过remove方法删除。

注意:如果是非admin账户删除数据,需要在数据库中待操作表的`db schema`中要配置permission权限,赋予delete为true。

指定要删除的记录有2种方式:

#### 方式1 通过指定文档ID删除

collection.doc(_id).remove()

删除单条记录

```js
const db = uniCloud.database();
db.collection("table1").doc("5f79fdb337d16d0001899566").remove()
```

删除该表所有数据
```js
const db = uniCloud.database();
let collection = db.collection("table1")
let res = await collection.get()
res.data.map(async(document) => {
  return await collection.doc(document.id).remove();
});
```

#### 方式2 条件查找文档后删除

collection.where().remove()

```js
// 删除字段a的值大于2的文档
try {
	await db.collection("table1").where("a>2").remove()
} catch (e) {
	uni.showModal({
		title: '提示',
		content: e.message
	})
}
```

#### 回调的res响应参数

| 字段		| 类型		| 必填	| 说明						|
| ---------	| -------	| ----	| ------------------------	|
雪洛's avatar
雪洛 已提交
1889
| deleted	| Number	| 否	| 删除的记录数量			|
W
wanganxp 已提交
1890 1891 1892 1893 1894

示例:判断删除成功或失败,打印删除的记录数量

```js
const db = uniCloud.database();
雪洛's avatar
雪洛 已提交
1895 1896 1897 1898 1899
db.collection("table1")
  .where({
    _id: "5f79fdb337d16d0001899566"
  })
  .remove()
W
wanganxp 已提交
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916
	.then((res) => {
		uni.showToast({
			title: '删除成功'
		})
		console.log("删除条数: ",res.deleted);
	}).catch((err) => {
		uni.showModal({
			content: err.message || '删除失败',
			showCancel: false
		})
	}).finally(() => {
		
	})
```

### 更新数据记录update

雪洛's avatar
雪洛 已提交
1917
获取到db的表对象,然后指定要更新的记录,通过update方法更新。
W
wanganxp 已提交
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938

注意:如果是非admin账户修改数据,需要在数据库中待操作表的`db schema`中要配置permission权限,赋予update为true。

collection.doc().update(Object data)

**参数说明**

| 参数 | 类型   | 必填 | 说明                                     |
| ---- | ------ | ---- | ---------------------------------------- |
| data | object | 是   | 更新字段的Object,{'name': 'Ben'} _id 非必填|

**回调的res响应参数**

| 参数	| 类型	|  说明																			|
| ----	| ------|  ----------------------------------------	|
|updated| Number| 更新成功条数,数据更新前后没变化时会返回0。用法与删除数据的响应参数示例相同	|


```js
const db = uniCloud.database();
let collection = db.collection("table1")
雪洛's avatar
雪洛 已提交
1939 1940 1941 1942 1943 1944 1945
let res = await collection.where({_id:'doc-id'})
  .update({
    name: "Hey",
    count: {
      fav: 1
    }
  });
W
wanganxp 已提交
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
```

```json
// 更新前的数据
{
  "_id": "doc-id",
  "name": "Hello",
  "count": {
    "fav": 0,
    "follow": 0
  }
}

// 更新后的数据
{
  "_id": "doc-id",
  "name": "Hey",
  "count": {
    "fav": 1,
    "follow": 0
  }
}
```

更新数组时,以数组下标作为key即可,比如以下示例将数组arr内下标为1的值修改为 uniCloud

```js
const db = uniCloud.database();
let collection = db.collection("table1")
雪洛's avatar
雪洛 已提交
1975 1976 1977 1978 1979 1980
let res = await collection.where({_id:'doc-id'})
  .update({
    arr: {
      1: "uniCloud"
    }
  })
W
wanganxp 已提交
1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
```

```json
// 更新前
{
  "_id": "doc-id",
  "arr": ["hello", "world"]
}
// 更新后
{
  "_id": "doc-id",
  "arr": ["hello", "uniCloud"]
}
```

#### 批量更新文档

```js
const db = uniCloud.database();
let collection = db.collection("table1")
let res = await collection.where("name=='hey'").update({
  age: 18,
})
```

#### 更新数组内指定下标的元素

```js
const db = uniCloud.database();
雪洛's avatar
雪洛 已提交
2010 2011 2012 2013 2014 2015 2016
const res = await db.collection('table1').where({_id:'1'})
  .update({
    // 更新students[1]
    ['students.' + 1]: {
      name: 'wang'
    }
  })
W
wanganxp 已提交
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
```

```json
// 更新前
{
  "_id": "1",
  "students": [
    {
      "name": "zhang"
    },
    {
      "name": "li"
    }
  ]
}

// 更新后
{
  "_id": "1",
  "students": [
    {
      "name": "zhang"
    },
    {
      "name": "wang"
    }
  ]
}
```

#### 更新数组内匹配条件的元素

**注意:只可确定数组内只会被匹配到一个的时候使用**

```js
const db = uniCloud.database();
const res = await db.collection('table1').where({
	'students.id': '001'
}).update({
  // 将students内id为001的name改为li
	'students.$.name': 'li'
})
```


```js
// 更新前
{
  "_id": "1",
  "students": [
    {
      "id": "001",
      "name": "zhang"
    },
    {
      "id": "002",
      "name": "wang"
    }
  ]
}

// 更新后
{
  "_id": "1",
  "students": [
    {
      "id": "001",
      "name": "li"
    },
    {
      "id": "002",
      "name": "wang"
    }
  ]
}
```

注意:
- 为方便控制权限,禁止前端使用set方法,一般情况下也不需要前端使用set
- 更新数据库时不可使用更新操作符`db.command.inc`
- 更新数据时键值不可使用`{'a.b.c': 1}`的形式,需要写成`{a:{b:{c:1}}}`形式(后续会对此进行优化)

雪洛's avatar
雪洛 已提交
2099
### MongoDB聚合操作
雪洛's avatar
雪洛 已提交
2100

W
wanganxp 已提交
2101
clientDB API支持使用聚合操作读取数据,关于聚合操作请参考[聚合操作](uniCloud/cf-database.md?id=aggregate)
雪洛's avatar
雪洛 已提交
2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118

例:取status等于1的随机20条数据

```js
const db = uniCloud.database()
const res = await db.collection('test').aggregate()
.match({
  status: 1
})
.sample({
  size: 20
})
.end()
```

**注意**

雪洛's avatar
雪洛 已提交
2119
- 目前`<uni-clientdb>`组件暂不支持使用直接aggregate方法进行聚合操作,但是可以使用JQL进行联表查询、分组统计、数据去重等功能
雪洛's avatar
雪洛 已提交
2120

雪洛's avatar
雪洛 已提交
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137
### 刷新token@refreshtoken

透传uni-id自动刷新的token给客户端

**用法**

```js
const db = uniCloud.database()

function refreshToken({
  token,
  tokenExpired
}) {
  uni.setStorageSync('uni_id_token', token)
  uni.setStorageSync('uni_id_token_expired', tokenExpired)
}
// 绑定刷新token事件
雪洛's avatar
雪洛 已提交
2138
db.on('refreshToken', refreshToken)
雪洛's avatar
雪洛 已提交
2139
// 解绑刷新token事件
雪洛's avatar
雪洛 已提交
2140 2141 2142
db.off('refreshToken', refreshToken)
```

雪洛's avatar
雪洛 已提交
2143
**注意:HBuilderX 3.0.0之前请使用db.auth.on、db.auth.off,HBuilderX 3.0.0以上版本仍兼容旧写法,但是推荐使用新写法db.on**
雪洛's avatar
雪洛 已提交
2144 2145 2146

### 错误处理@error

雪洛's avatar
雪洛 已提交
2147
全局clientDB错误事件,HBuilderX 3.0.0起支持。
雪洛's avatar
雪洛 已提交
2148 2149 2150 2151 2152 2153 2154

**用法**

```js
const db = uniCloud.database()

function onDBError({
雪洛's avatar
雪洛 已提交
2155
  code, // 错误码详见https://uniapp.dcloud.net.cn/uniCloud/clientdb?id=returnvalue
雪洛's avatar
雪洛 已提交
2156 2157 2158 2159 2160 2161 2162 2163
  message
}) {
  // 处理错误
}
// 绑定clientDB错误事件
db.on('error', onDBError)
// 解绑clientDB错误事件
db.off('error', onDBError)
雪洛's avatar
雪洛 已提交
2164 2165
```

雪洛's avatar
雪洛 已提交
2166
<!-- ### 处理错误@error
雪洛's avatar
雪洛 已提交
2167

雪洛's avatar
雪洛 已提交
2168
clientDB出现错误时触发,`HBuilderX 2.9.12+` 支持
雪洛's avatar
雪洛 已提交
2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187

**用法**

```js
const db = uniCloud.database()

function onError({
  code, // 错误码详见https://uniapp.dcloud.net.cn/uniCloud/clientdb?id=returnvalue
  message
}) {
  uni.showModal({
    content: message,
    showCancel: false
  })
}
// 绑定错误处理事件
db.auth.on('error', onError)
// 解绑错误处理事件
db.auth.off('error', onError)
雪洛's avatar
雪洛 已提交
2188
``` -->
雪洛's avatar
雪洛 已提交
2189

W
wanganxp 已提交
2190
## DBSchema@schema
雪洛's avatar
雪洛 已提交
2191

W
wanganxp 已提交
2192
`DB Schema`是基于 JSON 格式定义的数据结构的规范。
W
wanganxp 已提交
2193

W
wanganxp 已提交
2194
它有很多重要的作用:
W
wanganxp 已提交
2195

W
wanganxp 已提交
2196 2197 2198 2199 2200 2201
- 描述现有的数据格式。可以一目了然的阅读每个表、每个字段的用途。
- 设定数据操作权限(permission)。什么样的角色可以读/写哪些数据,都在这里配置。
- 设定字段值域能接受的格式(validator),比如不能为空、需符合指定的正则格式。
- 设置数据的默认值(defaultValue/forceDefaultValue),比如服务器当前时间、当前用户id等。
- 设定多个表的字段间映射关系(foreignKey),将多个表按一个虚拟表直接查询,大幅简化联表查询。
- 根据schema自动生成表单维护界面,比如新建页面和编辑页面,自动处理校验规则。
W
wanganxp 已提交
2202 2203

这些工具大幅减少了开发者的开发工作量和重复劳动。
雪洛's avatar
雪洛 已提交
2204

W
wanganxp 已提交
2205
**`DB Schema`是`clientDB`紧密相关的配套,掌握clientDB离不开详读[DB Schema文档](uniCloud/schema)。**
雪洛's avatar
雪洛 已提交
2206

W
wanganxp 已提交
2207
**下面示例中使用了注释,实际使用时schema是一个标准的json文件不可使用注释。**完整属性参考[schema字段](https://uniapp.dcloud.net.cn/uniCloud/schema?id=segment)
雪洛's avatar
雪洛 已提交
2208 2209 2210 2211 2212 2213

```js
{
  "bsonType": "object", // 表级的类型,固定为object
  "required": ['book', 'quantity'], // 新增数据时必填字段
  "permission": { // 表级权限
雪洛's avatar
雪洛 已提交
2214 2215 2216 2217
    "read": true, // 读
    "create": false, // 新增
    "update": false, // 更新
    "delete": false, // 删除
雪洛's avatar
雪洛 已提交
2218 2219 2220 2221 2222
  },
  "properties": { // 字段列表,注意这里是对象
    "book": { // 字段名book
      "bsonType": "string", // 字段类型
      "permission": { // 字段权限
雪洛's avatar
雪洛 已提交
2223 2224
        "read": true, // 字段读权限
        "write": false, // 字段写权限
雪洛's avatar
雪洛 已提交
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
      },
      "foreignKey": "book._id" // 其他表的关联字段
    },
    "quantity": {
      "bsonType": "int"
    }
  }
}
```

W
wanganxp 已提交
2235
### permission@permission
雪洛's avatar
雪洛 已提交
2236

W
wanganxp 已提交
2237
`DB Schema`中的数据权限配置功能非常强大,请详读[DB Schema的数据权限控制](uniCloud/schema?id=permission)
雪洛's avatar
雪洛 已提交
2238

W
wanganxp 已提交
2239
在配置好`DB Schema`的权限后,clientDB的查询写法,尤其是非`JQL`的聚合查询写法有些限制,具体如下:
雪洛's avatar
雪洛 已提交
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
- 不使用聚合时collection方法之后需紧跟一个where方法,这个where方法内传入的条件必须满足权限控制规则
- 使用聚合时aggregate方法之后需紧跟一个match方法,这个match方法内的条件需满足权限控制规则
- 使用lookup时只可以使用拼接子查询的写法(let+pipeline模式),做这个限制主要是因为需要确保访问需要lookup的表时也会传入查询条件,即pipeline参数里面`db.command.pipeline()`之后的match方法也需要像上一条里面的match一样限制
- 上面用于校验权限的match和where后的project和field是用来确定本次查询需要访问什么字段的(如果没有将会认为是在访问所有字段),访问的字段列表会用来确认使用那些字段权限校验。这个位置的project和field只能使用白名单模式
- 上面用于校验权限的match和where内如果有使用`db.command.expr`,那么在进行权限校验时expr方法内部的条件会被忽略,整个expr方法转化成一个不与任何条件产生交集的特别表达式,具体表现请看下面示例

**schema内permission配置示例**

```js
// order表schema
{
  "bsonType": "object", // 表级的类型,固定为object
  "required": ['book', 'quantity'], // 新增数据时必填字段
  "permission": { // 表级权限
雪洛's avatar
雪洛 已提交
2254 2255 2256 2257
    "read": "doc.uid == auth.uid", // 每个用户只能读取用户自己的数据。前提是要操作的数据doc,里面有一个字段存放了uid,即uni-id的用户id。(不配置时等同于false)
    "create": false, // 禁止新增数据记录(不配置时等同于false)
    "update": false, // 禁止更新数据(不配置时等同于false)
    "delete": false, // 禁止删除数据(不配置时等同于false)
W
wanganxp 已提交
2258
	"count": false, // 禁止对本表进行count计数
雪洛's avatar
雪洛 已提交
2259 2260 2261 2262 2263
  },
  "properties": { // 字段列表,注意这里是对象
    "secret_field": { // 字段名
      "bsonType": "string", // 字段类型
      "permission": { // 字段权限
雪洛's avatar
雪洛 已提交
2264 2265
        "read": false, // 禁止读取secret_field字段的数据
        "write": false // 禁止写入(包括更新和新增)secret_field字段的数据,父级节点存在false时这里可以不配
雪洛's avatar
雪洛 已提交
2266
      }
雪洛's avatar
雪洛 已提交
2267 2268 2269 2270 2271 2272 2273 2274
    },
    "uid":{
      "bsonType": "string", // 字段类型
      "foreignKey": "uni-id-users._id"
    },
    "book_id": {
      "bsonType": "string", // 字段类型
      "foreignKey": "book._id"
雪洛's avatar
雪洛 已提交
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
    }
  }
}
```

```js
// book表schema
{
  "bsonType": "object",
  "required": ['book', 'quantity'], // 新增数据时必填字段
  "permission": { // 表级权限
雪洛's avatar
雪洛 已提交
2286
    "read": "doc.status == 'OnSell'" // 允许所有人读取状态是OnSell的数据
雪洛's avatar
雪洛 已提交
2287 2288
  },
  "properties": { // 字段列表,注意这里是对象
雪洛's avatar
雪洛 已提交
2289 2290 2291 2292 2293 2294
    "title": {
      "bsonType": "string"
    },
    "author": {
      "bsonType": "string"
    },
雪洛's avatar
雪洛 已提交
2295 2296 2297
    "secret_field": { // 字段名
      "bsonType": "string", // 字段类型
      "permission": { // 字段权限
雪洛's avatar
雪洛 已提交
2298 2299
        "read": false, // 禁止读取secret_field字段的数据
        "write": false // 禁止写入(包括更新和新增)secret_field字段的数据
雪洛's avatar
雪洛 已提交
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312
      }
    }
  }
}
```

**请求示例**

```js
const db = uniCloud.database()
const dbCmd = db.command
const $ = dbCmd.aggregate
db.collection('order')
雪洛's avatar
雪洛 已提交
2313 2314 2315
  .where('uid == $env.uid && book_id.status == "OnSell"')
  .field('uid,book_id{title,author}')
  .get()
雪洛's avatar
雪洛 已提交
2316 2317
```

雪洛's avatar
雪洛 已提交
2318
在进行数据库操作之前,clientDB会使用permission内配置的规则对客户端操作进行一次校验,如果本次校验不通过还会通过数据库查询再进行一次校验
雪洛's avatar
雪洛 已提交
2319

雪洛's avatar
雪洛 已提交
2320
例1:
雪洛's avatar
雪洛 已提交
2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358

```js
// 数据库内news表有以下数据
{
  _id: "1",
  user_id: "uid_1",
  title: "abc"
}
```

```js
// news表对应的schema内做如下配置
{
  "bsonType": "object",
  "permission": { // 表级权限
    "read": true,
    "update": "doc.user_id == auth.uid" // 只允许修改自己的数据
  },
  "properties": {
    "user_id": {
      "bsonType": "string"
    },
    "title": {
      "bsonType": "string"
    }
  }
}
```

```js
// 用户ID为uid_1的用户在客户端使用如下操作
db.collection('news').doc('1').update({
  title: 'def'
})
```

此时客户端条件里面只有`doc._id == 1`,schema内又限制的`doc.user_id == auth.uid`,所以第一次预校验无法通过,会进行一次查库校验判断是否有权限进行操作。发现auth.uid确实和doc.user_id一致,上面的数据库操作允许执行。

雪洛's avatar
雪洛 已提交
2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
例2:

```js
// 数据库内goods表有以下数据
{
  _id: "1",
  name: "n1",
  status: 1
}
{
  _id: "2",
  name: "n2",
  status: 2
}
{
  _id: "3",
  name: "n3",
  status: 3
}
```

```js
// news表对应的schema内做如下配置
{
  "bsonType": "object",
  "permission": { // 表级权限
    "read": "doc.status > 1",
  },
  "properties": {
    "name": {
      "bsonType": "string"
    },
    "status": {
      "bsonType": "int"
    }
  }
}
```

```js
// 用户在客户端使用如下操作,可以通过第一次校验,不会触发查库校验
db.collection('goods').where('status > 1').get()

// 用户在客户端使用如下操作,无法通过第一次校验,会触发一次查库校验(原理大致是使用name == "n3" && status <= 1作为条件进行一次查询,如果有结果就认为没有权限访问,了解即可,无需深入)
db.collection('goods').where('name == "n3"').get()

// 用户在客户端使用如下操作,无法通过第一次校验,会触发一次查库校验,查库校验也会无法通过
db.collection('goods').where('name == "n1"').get()
```


雪洛's avatar
雪洛 已提交
2410
## action@action
雪洛's avatar
雪洛 已提交
2411

雪洛's avatar
雪洛 已提交
2412
action的作用是在执行前端发起的数据库操作时,额外触发一段云函数逻辑。它是一个可选模块。action是运行于云函数内的,可以使用云函数内的所有接口。
W
wanganxp 已提交
2413

W
wanganxp 已提交
2414 2415 2416 2417 2418
当一个前端操作数据库的方式不能完全满足需求,仍然同时需要在云端再执行一些云函数时,就在前端发起数据库操作时,通过`db.action("someactionname")`方式要求云端同时执行这个叫someactionname的action。还可以在权限规则内指定某些操作必须使用指定的action,比如`"action in ['action-a','action-b']"`,来达到更灵活的权限控制。

**注意action方法是db对象的方法,只能跟在db后面,不能跟在collection()后面**
- 正确:`db.action("someactionname").collection('table1')`
- 错误:`db.collection('table1').action("someactionname")`
W
wanganxp 已提交
2419

雪洛's avatar
雪洛 已提交
2420 2421
**尽量不要在action中使用全局变量,如果一定要用请务必确保自己已经阅读并理解了[云函数的启动模式](uniCloud/cf-functions.md?id=launchtype)**

W
wanganxp 已提交
2422
如果使用`<uni-clientdb>组件`,该组件也有action属性,设置action="someactionname"即可。
W
wanganxp 已提交
2423 2424 2425
```html
<uni-clientdb ref="udb" collection="table1" action="someactionname" v-slot:default="{data,pagination,loading,error}">
```
雪洛's avatar
雪洛 已提交
2426

雪洛's avatar
雪洛 已提交
2427
action支持一次使用多个,比如使用`db.action("action-a,action-b")`,其执行流程为`action-a.before->action-b.before->执行数据库操作->action-b.after->action-a.after`。在任一before环节抛出错误直接进入after流程,在after流程内抛出的错误会被传到下一个after流程。
雪洛's avatar
雪洛 已提交
2428

W
wanganxp 已提交
2429 2430
action是一种特殊的云函数,它不占用服务空间的云函数数量。

W
wanganxp 已提交
2431
目前action还不支持本地运行。后续会支持。
W
wanganxp 已提交
2432 2433

**新建action**
雪洛's avatar
雪洛 已提交
2434

W
wanganxp 已提交
2435
![新建action](https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/b6846d00-1460-11eb-b997-9918a5dda011.jpg)
雪洛's avatar
雪洛 已提交
2436

W
wanganxp 已提交
2437
每个action在uni-clientDB-actions目录下存放一个以action名称命名的js文件。
雪洛's avatar
雪洛 已提交
2438

W
wanganxp 已提交
2439
在这个js文件的代码里,包括before和after两部分,分别代表clientDB具体操作数据库前和后。
雪洛's avatar
雪洛 已提交
2440

W
wanganxp 已提交
2441
- before在clientDB执行前触发,before里的代码执行完毕后再开始操作数据库。before的常用用途:
W
wanganxp 已提交
2442
	* 对前端传入的数据进行二次处理
雪洛's avatar
雪洛 已提交
2443
	* 在此处开启数据库事务,万一操作数据库失败,可以在after里回滚
L
linju-json 已提交
2444
	* 使用throw阻止运行
W
wanganxp 已提交
2445
	* 如果权限或字段值域校验不想配在schema和validateFunction里,也可以在这里做校验
雪洛's avatar
雪洛 已提交
2446
	
L
linju-json 已提交
2447
- after在clientDB执行后触发,clientDB操作数据库后触发after里的代码。after的常用用途:
W
wanganxp 已提交
2448
	* 对将要返回给前端的数据进行二次处理
雪洛's avatar
雪洛 已提交
2449 2450 2451 2452 2453 2454 2455 2456
	* 也可以在此处处理错误,回滚数据库事务
	* 对数据库进行二次操作,比如前端查询一篇文章详情后,在此处对文章的阅读数+1。因为permission里定义,一般是要禁止前端操作文章的阅读数字段的,此时就应该通过action,在云函数里对阅读数+1

示例:

```js
// 客户端发起请求,给todo表新增一行数据,同时指定action为add-todo
const db = uniCloud.database()
W
wanganxp 已提交
2457
db.action('add-todo') //注意action方法是db的方法,只能跟在db后面,不能跟在collection()后面
雪洛's avatar
雪洛 已提交
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
  .collection('todo')
  .add({
    title: 'todo title'
  })
  .then(res => {
    console.log(res)
  }).catch(err => {
    console.error(err)
  })
```

```js
W
wanganxp 已提交
2470
// 一个action文件示例 uni-clientDB-actions/add-todo.js
雪洛's avatar
雪洛 已提交
2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
module.exports = {
  // 在数据库操作之前执行
  before: async(state,event)=>{
    // state为当前clientDB操作状态其格式见下方说明
    // event为传入云函数的event对象
    
    // before内可以操作state上的newData对象对数据进行修改,比如:
    state.newData.create_time = Date.now()
    // 指定插入或修改的数据内的create_time为Date.now()
    // 执行了此操作之后实际插入的数据会变成 {title: 'todo title', create_time: xxxx}
W
wanganxp 已提交
2481
    // 实际上,这个场景,有更简单的实现方案:在db schema内配置defaultValue或者forceDefaultValue,即可自动处理新增记录使用当前服务器时间
雪洛's avatar
雪洛 已提交
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493
  },
  // 在数据库操作之后执行
  after:async (state,event,error,result)=>{
    // state为当前clientDB操作状态其格式见下方说明
    // event为传入云函数的event对象
    // error为执行操作的错误对象,如果没有错误error的值为null
    // result为执行command返回的结果
    
    if(error) {
      throw error
    }
    
W
wanganxp 已提交
2494
    // after内可以对result进行额外处理并返回
雪洛's avatar
雪洛 已提交
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508
    result.msg = 'hello'
    return result
  }
}
```

**state**参数说明

```js
// state参数格式如下
{
  command: {
    // getMethod('where') 获取所有的where方法,返回结果为[{$method:'where',$param: [{a:1}]}]
    getMethod,
W
wanganxp 已提交
2509
    // getParam({name:'where',index: 0}) 获取第1个where方法的参数,结果为数组形式,例:[{a:1}]
雪洛's avatar
雪洛 已提交
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
    getParam,
    // setParam({name:'where',index: 0, param: [{a:1}]}) 设置第1个where方法的参数,调用之后where方法实际形式为:where({a:1})
    setParam
  },
  // 需要注意的是clientDB可能尚未获取用户信息,如果权限规则内没使用auth对象且数据库指令里面没使用db.env.uid则clientDB不会自动取获取用户信息
  auth: {
    uid, // 用户ID,如果未获取或者获取失败uid值为null
    role, // 通过uni-id获取的用户角色,需要使用1.1.9以上版本的uni-id,如果未获取或者获取失败role值为[]
    permission // 通过uni-id获取的用户权限,需要使用1.1.9以上版本的uni-id,如果未获取或者获取失败permission值为[],注意登录时传入needPermission才可以获取permission,请参考 https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=rbac
  },
  // 事务对象,如果需要用到事务可以在action的before内使用state.transaction = await db.startTransaction()传入
  transaction,
  // 更新或新增的数据
  newData,
  // 访问的集合
  collection,
  // 操作类型,可能的值'read'、'create'、'update'、'delete'
  type
}
```
雪洛's avatar
雪洛 已提交
2530

雪洛's avatar
雪洛 已提交
2531 2532
**如需在before和after内传参,建议直接在state上挂载。但是切勿覆盖上述属性**

雪洛's avatar
雪洛 已提交
2533 2534
## 可用聚合操作符列表@aggregate-operator

W
wanganxp 已提交
2535
为方便书写,clientDB内将聚合操作符的用法进行了简化(相对于云函数内使用聚合操作符而言),主要是参数摊平。以下是可以在clientDB中使用的聚合操作符
雪洛's avatar
雪洛 已提交
2536

雪洛's avatar
雪洛 已提交
2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631
|操作符						|详细文档(云函数内用法)																			|JQL简化用法																																								|说明																									|
|---							|---																													|---																																												|---																									|
|abs							|[abs](uniCloud/cf-database.md?id=abs)												|abs(表达式)																																								|-																										|
|add							|[add](uniCloud/cf-database.md?id=add-1)											|add(表达式1,表达式2)																																				|-																										|
|ceil							|[ceil](uniCloud/cf-database.md?id=ceil)											|ceil(表达式)																																								|-																										|
|divide						|[divide](uniCloud/cf-database.md?id=divide)									|divide(表达式1,表达式2)																																		|-																										|
|exp							|[exp](uniCloud/cf-database.md?id=exp)												|exp(表达式)																																								|-																										|
|floor						|[floor](uniCloud/cf-database.md?id=floor)										|floor(表达式)																																							|-																										|
|ln								|[ln](uniCloud/cf-database.md?id=ln)													|ln(表达式)																																									|-																										|
|log							|[log](uniCloud/cf-database.md?id=log)												|log(表达式1,表达式2)																																				|-																										|
|log10						|[log10](uniCloud/cf-database.md?id=log10)										|log10(表达式)																																							|-																										|
|mod							|[mod](uniCloud/cf-database.md?id=mod)												|mod(表达式1,表达式2)																																				|-																										|
|multiply					|[multiply](uniCloud/cf-database.md?id=multiply)							|multiply(表达式1,表达式2)																																	|-																										|
|pow							|[pow](uniCloud/cf-database.md?id=pow)												|pow(表达式1,表达式2)																																				|-																										|
|sqrt							|[sqrt](uniCloud/cf-database.md?id=sqrt)											|sqrt(表达式1,表达式2)																																			|-																										|
|subtract					|[subtract](uniCloud/cf-database.md?id=subtract)							|subtract(表达式1,表达式2)																																	|-																										|
|trunc						|[trunc](uniCloud/cf-database.md?id=trunc)										|trunc(表达式)																																							|-																										|
|arrayElemAt			|[arrayElemAt](uniCloud/cf-database.md?id=arrayelemat)				|arrayElemAt(表达式1,表达式2)																																|-																										|
|arrayToObject		|[arrayToObject](uniCloud/cf-database.md?id=arraytoobject)		|arrayToObject(表达式)																																			|-																										|
|concatArrays			|[concatArrays](uniCloud/cf-database.md?id=concatarrays)			|concatArrays(表达式1,表达式2)																															|-																										|
|filter						|[filter](uniCloud/cf-database.md?id=filter)									|filter(input,as,cond)																																			|-																										|
|in								|[in](uniCloud/cf-database.md?id=in)													|in(表达式1,表达式2)																																				|-																										|
|indexOfArray			|[indexOfArray](uniCloud/cf-database.md?id=indexofarray)			|indexOfArray(表达式1,表达式2)																															|-																										|
|isArray					|[isArray](uniCloud/cf-database.md?id=isarray)								|isArray(表达式)																																						|-																										|
|map							|[map](uniCloud/cf-database.md?id=map)												|map(input,as,in)																																						|-																										|
|objectToArray		|[objectToArray](uniCloud/cf-database.md?id=objecttoarray)		|objectToArray(表达式)																																			|-																										|
|range						|[range](uniCloud/cf-database.md?id=range)										|range(表达式1,表达式2)																																			|-																										|
|reduce						|[reduce](uniCloud/cf-database.md?id=reduce)									|reduce(input,initialValue,in)																															|-																										|
|reverseArray			|[reverseArray](uniCloud/cf-database.md?id=reversearray)			|reverseArray(表达式)																																				|-																										|
|size							|[size](uniCloud/cf-database.md?id=size)											|size(表达式)																																								|-																										|
|slice						|[slice](uniCloud/cf-database.md?id=slice)										|slice(表达式1,表达式2)																																			|-																										|
|zip							|[zip](uniCloud/cf-database.md?id=zip)												|zip(inputs,useLongestLength,defaults)																											|-																										|
|and							|[and](uniCloud/cf-database.md?id=and)												|and(表达式1,表达式2)																																				|-																										|
|not							|[not](uniCloud/cf-database.md?id=not)												|not(表达式)																																								|-																										|
|or								|[or](uniCloud/cf-database.md?id=or)													|or(表达式1,表达式2)																																				|-																										|
|cmp							|[cmp](uniCloud/cf-database.md?id=cmp)												|cmp(表达式1,表达式2)																																				|-																										|
|eq								|[eq](uniCloud/cf-database.md?id=eq)													|eq(表达式1,表达式2)																																				|-																										|
|gt								|[gt](uniCloud/cf-database.md?id=gt)													|gt(表达式1,表达式2)																																				|-																										|
|gte							|[gte](uniCloud/cf-database.md?id=gte)												|gte(表达式1,表达式2)																																				|-																										|
|lt								|[lt](uniCloud/cf-database.md?id=lt)													|lt(表达式1,表达式2)																																				|-																										|
|lte							|[lte](uniCloud/cf-database.md?id=lte)												|lte(表达式1,表达式2)																																				|-																										|
|neq							|[neq](uniCloud/cf-database.md?id=neq)												|neq(表达式1,表达式2)																																				|-																										|
|cond							|[cond](uniCloud/cf-database.md?id=cond)											|cond(表达式1,表达式2)																																			|-																										|
|ifNull						|[ifNull](uniCloud/cf-database.md?id=ifnull)									|ifNull(表达式1,表达式2)																																		|-																										|
|switch						|[switch](uniCloud/cf-database.md?id=switch)									|switch(branches,default)																																		|-																										|
|dateFromParts		|[dateFromParts](uniCloud/cf-database.md?id=datefromparts)		|dateFromParts(year,month,day,hour,minute,second,millisecond,timezone)											|-																										|
|isoDateFromParts	|[dateFromParts](uniCloud/cf-database.md?id=datefromparts)		|isoDateFromParts(isoWeekYear,isoWeek,isoDayOfWeek,hour,minute,second,millisecond,timezone)	|云函数内此操作符对应dateFromParts,仅JQL字符串内支持	|
|dateFromString		|[dateFromString](uniCloud/cf-database.md?id=datefromstring)	|dateFromString(dateString,format,timezone,onError,onNull)																	|-																										|
|dateToString			|[dateToString](uniCloud/cf-database.md?id=datetostring)			|dateToString(date,format,timezone,onNull)																									|-																										|
|dayOfMonth				|[dayOfMonth](uniCloud/cf-database.md?id=dayofmonth)					|dayOfMonth(date,timezone)																																	|-																										|
|dayOfWeek				|[dayOfWeek](uniCloud/cf-database.md?id=dayofweek)						|dayOfWeek(date,timezone)																																		|-																										|
|dayOfYear				|[dayOfYear](uniCloud/cf-database.md?id=dayofyear)						|dayOfYear(date,timezone)																																		|-																										|
|hour							|[hour](uniCloud/cf-database.md?id=hour)											|hour(date,timezone)																																				|-																										|
|isoDayOfWeek			|[isoDayOfWeek](uniCloud/cf-database.md?id=isodayofweek)			|isoDayOfWeek(date,timezone)																																|-																										|
|isoWeek					|[isoWeek](uniCloud/cf-database.md?id=isoweek)								|isoWeek(date,timezone)																																			|-																										|
|isoWeekYear			|[isoWeekYear](uniCloud/cf-database.md?id=isoweekyear)				|isoWeekYear(date,timezone)																																	|-																										|
|millisecond			|[millisecond](uniCloud/cf-database.md?id=millisecond)				|millisecond(date,timezone)																																	|-																										|
|minute						|[minute](uniCloud/cf-database.md?id=minute)									|minute(date,timezone)																																			|-																										|
|month						|[month](uniCloud/cf-database.md?id=month)										|month(date,timezone)																																				|-																										|
|second						|[second](uniCloud/cf-database.md?id=second)									|second(date,timezone)																																			|-																										|
|week							|[week](uniCloud/cf-database.md?id=week)											|week(date,timezone)																																				|-																										|
|year							|[year](uniCloud/cf-database.md?id=year)											|year(date,timezone)																																				|-																										|
|timestampToDate	|-																														|timestampToDate(timestamp)																																	|仅JQL字符串内支持,HBuilderX 3.1.0起支持							|
|literal					|[literal](uniCloud/cf-database.md?id=literal)								|literal(表达式)																																						|-																										|
|mergeObjects			|[mergeObjects](uniCloud/cf-database.md?id=mergeobjects)			|mergeObjects(表达式1,表达式2)																															|-																										|
|allElementsTrue	|[allElementsTrue](uniCloud/cf-database.md?id=allelementstrue)|allElementsTrue(表达式1,表达式2)																														|-																										|
|anyElementTrue		|[anyElementTrue](uniCloud/cf-database.md?id=anyelementtrue)	|anyElementTrue(表达式1,表达式2)																														|-																										|
|setDifference		|[setDifference](uniCloud/cf-database.md?id=setdifference)		|setDifference(表达式1,表达式2)																															|-																										|
|setEquals				|[setEquals](uniCloud/cf-database.md?id=setequals)						|setEquals(表达式1,表达式2)																																	|-																										|
|setIntersection	|[setIntersection](uniCloud/cf-database.md?id=setintersection)|setIntersection(表达式1,表达式2)																														|-																										|
|setIsSubset			|[setIsSubset](uniCloud/cf-database.md?id=setissubset)				|setIsSubset(表达式1,表达式2)																																|-																										|
|setUnion					|[setUnion](uniCloud/cf-database.md?id=setunion)							|setUnion(表达式1,表达式2)																																	|-																										|
|concat						|[concat](uniCloud/cf-database.md?id=concat)									|concat(表达式1,表达式2)																																		|-																										|
|indexOfBytes			|[indexOfBytes](uniCloud/cf-database.md?id=indexofbytes)			|indexOfBytes(表达式1,表达式2)																															|-																										|
|indexOfCP				|[indexOfCP](uniCloud/cf-database.md?id=indexofcp)						|indexOfCP(表达式1,表达式2)																																	|-																										|
|split						|[split](uniCloud/cf-database.md?id=split)										|split(表达式1,表达式2)																																			|-																										|
|strLenBytes			|[strLenBytes](uniCloud/cf-database.md?id=strlenbytes)				|strLenBytes(表达式)																																				|-																										|
|strLenCP					|[strLenCP](uniCloud/cf-database.md?id=strlencp)							|strLenCP(表达式)																																						|-																										|
|strcasecmp				|[strcasecmp](uniCloud/cf-database.md?id=strcasecmp)					|strcasecmp(表达式1,表达式2)																																|-																										|
|substr						|[substr](uniCloud/cf-database.md?id=substr)									|substr(表达式1,表达式2)																																		|-																										|
|substrBytes			|[substrBytes](uniCloud/cf-database.md?id=substrbytes)				|substrBytes(表达式1,表达式2)																																|-																										|
|substrCP					|[substrCP](uniCloud/cf-database.md?id=substrcp)							|substrCP(表达式1,表达式2)																																	|-																										|
|toLower					|[toLower](uniCloud/cf-database.md?id=tolower)								|toLower(表达式)																																						|-																										|
|toUpper					|[toUpper](uniCloud/cf-database.md?id=toupper)								|toUpper(表达式)																																						|-																										|
|addToSet					|[addToSet](uniCloud/cf-database.md?id=addtoset)							|addToSet(表达式)																																						|-																										|
|avg							|[avg](uniCloud/cf-database.md?id=avg)												|avg(表达式)																																								|-																										|
|first						|[first](uniCloud/cf-database.md?id=first)										|first(表达式)																																							|-																										|
|last							|[last](uniCloud/cf-database.md?id=last)											|last(表达式)																																								|-																										|
|max							|[max](uniCloud/cf-database.md?id=max)												|max(表达式)																																								|-																										|
|min							|[min](uniCloud/cf-database.md?id=min)												|min(表达式)																																								|-																										|
|push							|[push](uniCloud/cf-database.md?id=push)											|push(表达式)																																								|-																										|
|stdDevPop				|[stdDevPop](uniCloud/cf-database.md?id=stddevpop)						|stdDevPop(表达式)																																					|-																										|
|stdDevSamp				|[stdDevSamp](uniCloud/cf-database.md?id=stddevsamp)					|stdDevSamp(表达式)																																					|-																										|
|sum							|[sum](uniCloud/cf-database.md?id=sum)												|sum(表达式)																																								|-																										|
|let							|[let](uniCloud/cf-database.md?id=let)												|let(vars,in)																																								|-																										|
雪洛's avatar
雪洛 已提交
2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659

以上操作符还可以组合使用

例:数据表article内有以下数据

```js
{
  "_id": "1",
  "publish_date": 1611141512751,
  "content": "hello uniCloud content 01",
  "content": "hello uniCloud title 01",
}

{
  "_id": "2",
  "publish_date": 1611141512752,
  "content": "hello uniCloud content 02",
  "content": "hello uniCloud title 02",
}

{
  "_id": "3",
  "publish_date": 1611141512753,
  "content": "hello uniCloud content 03",
  "content": "hello uniCloud title 03",
}
```

W
wanganxp 已提交
2660
可以通过以下查询将publish_date字段从时间戳转为`2021-01-20`形式,然后进行按天进行统计
雪洛's avatar
雪洛 已提交
2661 2662 2663 2664 2665 2666 2667 2668

```js
const res = await db.collection('article')
.groupBy('dateToString(add(new Date(0),publish_date),"%Y-%m-%d","+0800") as publish_date_str')
.groupField('count(*) as total')
.get()
```

W
wanganxp 已提交
2669
上述代码使用add方法将publish_date时间戳转为日期类型,再用dateToString将上一步的日期按照时区'+0800'(北京时间),格式化为`4位年-2位月-2位日`格式,完整格式化参数请参考[dateToString](uniCloud/cf-database.md?id=datetostring)
雪洛's avatar
雪洛 已提交
2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685

上述代码执行结果为

```js
res = {
  result: {
    data: [{
      publish_date_str: '2021-01-20',
      total: 3
    }]
  }
}
```

### 累计器操作符@accumulator

雪洛's avatar
雪洛 已提交
2686 2687
累计器操作符一般用于统计汇总,一般在groupField内使用

雪洛's avatar
雪洛 已提交
2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699
|操作符				|详细文档																								|用法										|说明																|
|---					|---																										|---										|---																|
|addToSet			|[addToSet](uniCloud/cf-database.md?id=addtoset)				|addToSet(<表达式>)			|-																	|
|avg					|[avg](uniCloud/cf-database.md?id=avg)									|avg(<表达式>)					|-																	|
|first				|[first](uniCloud/cf-database.md?id=first)							|first(<表达式>)				|-																	|
|last					|[last](uniCloud/cf-database.md?id=last)								|last(<表达式>)					|-																	|
|max					|[max](uniCloud/cf-database.md?id=max)									|max(<表达式>)					|-																	|
|min					|[min](uniCloud/cf-database.md?id=min)									|min(<表达式>)					|-																	|
|push					|[push](uniCloud/cf-database.md?id=push)								|push(<表达式>)					|-																	|
|stdDevPop		|[stdDevPop](uniCloud/cf-database.md?id=stddevpop)			|stdDevPop(<表达式>)		|-																	|
|stdDevSamp		|[stdDevSamp](uniCloud/cf-database.md?id=stddevsamp)		|stdDevSamp(<表达式>)		|-																	|
|sum					|[sum](uniCloud/cf-database.md?id=sum)									|sum(<表达式>)					|-																	|
W
wanganxp 已提交
2700
|mergeObjects	|[mergeObjects](uniCloud/cf-database.md?id=mergeobjects)|mergeObjects(<表达式1>)|在groupField内使用时仅接收一个参数	|