db.command.aggregate.last
1. Operator Description
Function: Returns the value of the specified field from the last document in a set of documents. This operation is meaningful only when the set of documents is sorted by some definition (sort
).
Declaration: db.command.aggregate.last(<expression>)
Notes:
last
can only be used in thegroup
stage and is meaningful only when used withsort
.
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | Expression | Required | An expression is a string in the form of $ + specified field . |
3. Sample Code
Suppose the collection students
contains the following records:
{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }
To get the maximum score
value from all records, you can first sort all records by score
and then retrieve the last
value from the last record.
// Sample code in the Cloud Function environment
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: 'xxx'
})
const db = app.database()
const $ = db.command.aggregate
const _ = db.command
exports.main = async (event, context) => {
const res = await db
.collection('students')
.aggregate()
.sort({
score: 1
})
.group({
_id: null,
max: $.last('$score')
})
.end()
console.log(res.data)
}
The returned data result is as follows:
{ "_id": null, "max": 100 }