mongo.Aggregate.倚天剑.横扫千军
练功贵在坚持,凡在武学上面有很高造诣的,不外乎俩种人,一种天赋极高的,看一遍就会,达到武功精要,另外一种的就是勤奋的,假已时日,也能登峰造极,大多数人属于后者,气沉丹田,让我们一起来修行。。。
- 九阴白骨爪之$addFields
简介:在文档中添加新的字段
语法:{ $addFields: { <newField>: <expression>, ... } }
支持版本: 3.4
示例:
数据源:
{
_id: 1,
student: "Maya",
homework: [ 10, 5, 10 ],
quiz: [ 10, 8 ],
extraCredit:
}
{
_id: 2,
student: "Ryan",
homework: [ 5, 6, 5 ],
quiz: [ 8, 8 ],
extraCredit: 8
}
查询语句
db.scores.aggregate( [
{
$addFields: {
totalHomework: { $sum: "$homework" } ,
totalQuiz: { $sum: "$quiz" }
}
},
{
$addFields: { totalScore:
{ $add: [ "$totalHomework", "$totalQuiz", "$extraCredit" ] } }
}
] )
输出结果
{
"_id" : 1,
"student" : "Maya",
"homework" : [ 10, 5, 10 ],
"quiz" : [ 10, 8 ],
"extraCredit" : ,
"totalHomework" : 25,
"totalQuiz" : 18,
"totalScore" : 43
}
{
"_id" : 2,
"student" : "Ryan",
"homework" : [ 5, 6, 5 ],
"quiz" : [ 8, 8 ],
"extraCredit" : 8,
"totalHomework" : 16,
"totalQuiz" : 16,
"totalScore" : 40
}
相关文章