选择带有"group by"的Max().在mongodb中

编程入门 行业动态 更新时间:2024-10-24 16:27:33
本文介绍了选择带有"group by"的Max().在mongodb中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

请帮助我将此选择语句转换为mongodb:

Please help me to convert this select sentence to mongodb:

Select Name, Max(Value) From table1 Group By Name

我阅读了此文档: www.mongodb/display /DOCS/Aggregation#Aggregation-Group

但仍然不知道如何将Max()方法而不是SUM()用作该文档.

but still dont know how to apply Max() method instead SUM() as that document.

谢谢.

推荐答案

我已经如下创建了Mongo Collection.

I have created Mongo Collection as follows.

{ "_id" : ObjectId("4fb36bfd3d1c88bfa15103b1"), "name" : "bob", "value" : 5 } { "_id" : ObjectId("4fb36c033d1c88bfa15103b2"), "name" : "bob", "value" : 3 } { "_id" : ObjectId("4fb36c063d1c88bfa15103b3"), "name" : "bob", "value" : 7 } { "_id" : ObjectId("4fb36c0c3d1c88bfa15103b4"), "name" : "john", "value" : 2 } { "_id" : ObjectId("4fb36c103d1c88bfa15103b5"), "name" : "john", "value" : 4 } { "_id" : ObjectId("4fb36c143d1c88bfa15103b6"), "name" : "john", "value" : 8 } { "_id" : ObjectId("4fb36c163d1c88bfa15103b7"), "name" : "john", "value" : 6 }

然后通过使用以下代码,将其按名称和max(value)分组

Then by using the following code I group it by their name and max(value)

db.table1.group( {key: {name:true}, reduce: function(obj,prev) { if (prev.maxValue < obj.value) { prev.maxValue = obj.value; } }, initial: { maxValue: 0 }} );

结果显示为

[ { "name" : "bob", "maxValue" : 7 }, { "name" : "john", "maxValue" : 8 } ]

使用聚合框架要简单得多.通过使用聚合框架,可以通过以下代码获得相同的结果.

It is much simpler with the aggregation framework. You can get the same result with the following code by using aggregation framework.

db.table1.aggregate( {$group:{_id:"$name", "maxValue": {$max:"$value"}}} );

更多推荐

选择带有"group by"的Max().在mongodb中

本文发布于:2023-11-22 13:58:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617712.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:group   quot   mongodb   Max

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!