MongoDB聚合/数学运算求和特定学生的分数
总计,请aggregate()与$sum一起使用。让我们创建一个包含文档的集合-
> db.demo434.insertOne({"Name":"Chris","Score":45});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e771603bbc41e36cc3cae93")
}
> db.demo434.insertOne({"Name":"David","Score":55});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e77161abbc41e36cc3cae94")
}
> db.demo434.insertOne({"Name":"Chris","Score":55});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e771624bbc41e36cc3cae95")
}在find()方法的帮助下显示集合中的所有文档-
> db.demo434.find();
这将产生以下输出-
{ "_id" : ObjectId("5e771603bbc41e36cc3cae93"), "Name" : "Chris", "Score" : 45 }
{ "_id" : ObjectId("5e77161abbc41e36cc3cae94"), "Name" : "David", "Score" : 55 }
{ "_id" : ObjectId("5e771624bbc41e36cc3cae95"), "Name" : "Chris", "Score" : 55 }以下是特定学生的汤姆总和查询分数-
> db.demo434.aggregate([
... { "$match": { "Name": "Chris"} },
... { "$group": { "_id": null, "TotalScore": { "$sum": "$Score" } } }
... ]);这将产生以下输出-
{ "_id" : null, "TotalScore" : 100 }热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短