数据表:
{
"scores": { // 集合(表名)
"data": [ // 数据
{
"_id": 1,
"student": "Maya",
"homework": [10, 5, 10],
"quiz": [10, 8],
"extraCredit": 0
},
{
"_id": 2,
"student": "Ryan",
"homework": [5, 6, 5],
"quiz": [8, 8],
"extraCredit": 8
}
]
}
}
聚合操作:
‘use strict‘;
const db = uniCloud.database();
const $ = db.command.aggregate;
exports.main = async(event, context) => {
const msg = db.collection(‘scores‘).aggregate()
// 添加两个字段:
.addFields({
totalHomework: $.sum(‘$homework‘),
totalQuiz: $.sum(‘$quiz‘)
})
// 根据上面新添加的两个字段值在添加一个字段
.addFields({
totalScore: $.add([‘$totalHomework‘, ‘$totalQuiz‘, ‘$extraCredit‘])
})
.end();
return msg;
};
// 聚合之后的返回值
/*
{
"affectedDocs": 2,
"data": [{
"_id": 1,
"extraCredit": 0,
"homework": [10, 5, 10],
"quiz": [10, 8],
"student": "Maya",
"totalHomework": 25,
"totalQuiz": 18,
"totalScore": 43
}, {
"_id": 2,
"extraCredit": 8,
"homework": [5, 6, 5],
"quiz": [8, 8],
"student": "Ryan",
"totalHomework": 16,
"totalQuiz": 16,
"totalScore": 40
}]
}
*/