mongo聚合查询之 $addFields的作用:
大致说明:字面意思是添加字段,就是在查询的结果再添加一些字段信息,字段的内容自己决定,可能还是不能理解,下面上码
$addFields用法支持mongo3.4及以上的版本
1.这是字段统计式的用法
准备数据:
{ _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 }
执行命令:
db.scores.aggregate([ { $addFields: { totalHomework: { $sum: "$homework" }, // 给每个查询结果添加totalHomework字段,值为原文档对象中homework字段数组的和 totalQuiz: { $sum: "$quiz" }, // 同理,添加totalQuiz字段,值为quize数组字段的和 }, }, { $addFields: { totalScore: { $add: ["$totalHomework", "$totalQuiz", "$extraCredit"] }, }, // 再添加一个totalScore字段,值为上面的totalHomework,totalQuiz两个字段和原有字段extraCredit三个字段相加之和 }, ]);
结果:
{ "_id" : 1, "student" : "Maya", "homework" : [ 10, 5, 10 ], "quiz" : [ 10, 8 ], "extraCredit" : 0, "totalHomework" : 25, // homework之和 10+5+10 "totalQuiz" : 18, // quiz之和 10+8 "totalScore" : 43 // totalHome+totalQuiz+extraCredit之和 25+18+0 } { "_id" : 2, "student" : "Ryan", "homework" : [ 5, 6, 5 ], "quiz" : [ 8, 8 ], "extraCredit" : 8, "totalHomework" : 16, "totalQuiz" : 16, "totalScore" : 40 }
2.下面是给内嵌文档增加字段的用法:
准备数据:
{ _id: 1, type: "a", specs: { doors: 4} }
{ _id: 2, type: "b" }
执行命令:
db.vehicles.aggregate([ { $addFields: { "specs.fuel_type": "unleaded", // 内嵌对象specs添加一个fuel_type字段,值为'unleaded' }, }, ]);
查询结果:
{ _id: 1, type: "a", specs: { doors: 4, fuel_type: "unleaded" } } { _id: 2, type: "b", specs: { fuel_type: "unleaded" } }
3.覆盖已有的字段:
准备数据:
{ _id: 1, dogs: 10, cats: 15 }
执行命令:
db.animals.aggregate([ { $addFields: { cats: 20 }, }, ]);
结果:
{ _id: 1, dogs: 10, cats: 20 }
虽然是覆盖原有的字段,但并不会对数据做修改,大家放心
mongo官方原文链接:https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/