汇总框架,使参加考试的学生的名字比所有考试的总平均分数低一分
为此,您可以使用aggregate()。我们已经将测试记录视为“Value1”,“Value2”等。让我们创建包含文档的集合-
> db.demo432.insertOne(
... {
... "_id" : 101,
... "Name" : "David",
... "Value1" : 67,
... "Value2" : 87,
... "Value3" : 78
... }
... )
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo432.insertOne(
... {
... "_id" : 102,
... "Name" : "Sam",
... "Value1" : 98,
... "Value2" : 45,
... "Value3" : 90
... }
... )
{ "acknowledged" : true, "insertedId" : 102 }在find()方法的帮助下显示集合中的所有文档-
> db.demo432.find();
这将产生以下输出-
{ "_id" : 101, "Name" : "David", "Value1" : 67, "Value2" : 87, "Value3" : 78 }
{ "_id" : 102, "Name" : "Sam", "Value1" : 98, "Value2" : 45, "Value3" : 90 }以下是查询以使考试一分的学生的名字小于所有考试的平均值-
> db.demo432.aggregate([{
... $project: {
... Name: '$Name',
... Value1: '$Value1',
... average: {
... $avg: ['$Value1', '$Value2', '$Value3']
... }
... }
... },
... {
... $group: {
... _id: null,
... NameValue1: {
... $push: {
... "Name": "$Name",
... "Value1": "$Value1"
... }
... },
... totalAverage: {
... $avg: '$average'
... }
... }
... },
... { $project:
... { lessthanAverageNames:
... {
... $map:
... {
... input: {
... $filter: {
... input: "$NameValue1",
... as: "out",
... cond: {
... $lt: ["$$out.Value1", "$totalAverage"]
... }
... }
... },
... as: "o",
... in: "$$o.Name"
... }
... }
... }
... }
... ]);这将产生以下输出-
{ "_id" : null, "lessthanAverageNames" : [ "David" ] }