unicloud数组操作符arrayElemAt(可在udb前端组件中使用)

数组操作符

#arrayElemAt

返回在指定数组下标的元素。

#API 说明

语法如下:

db.command.aggregate.arrayElemAt([<array>, <index>])

复制代码

<array> 可以是任意解析为数组的表达式。

<index> 可以是任意解析为整形的表达式。如果是正数,arrayElemAt 返回在 index 位置的元素,如果是负数,arrayElemAt 返回从数组尾部算起的 index 位置的元素。

#示例代码

假设集合 exams 有如下记录:

{ "_id": 1, "scores": [80, 60, 65, 90] }
{ "_id": 2, "scores": [78] }
{ "_id": 3, "scores": [95, 88, 92] }

复制代码

求各个第一次考试的分数和和最后一次的分数:

const $ = db.command.aggregate
let res = await db.collection('exams').aggregate()
  .project({
    first: $.arrayElemAt(['$scores', 0]),
    last: $.arrayElemAt(['$scores', -1]),
  })
  .end()

复制代码

返回结果如下:

{ "_id": 1, "first": 80, "last": 90 }
{ "_id": 2, "first": 78, "last": 78 }
{ "_id": 3, "first": 95, "last": 92 }

udb前端组件中使用示例:

<unicloud-db v-slot:default="{data, loading, error, options}" 
collection="posts,uni-id-users" field="create_date,
arrayElemAt(author.username,0) as username"
:page-size="1">

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注