您现在的位置是:课程教程文章
mongodb 如何使用group by
2023-12-18 18:12课程教程文章 人已围观
-
【Side by Side】SBS朗文国际英语第三册(口
【Side by Side】SBS朗文国际英语第三册(口注意: 苹果IOS设备用户 购买会掉单 ,购买前请务必 加微信 购买。 微信:br... -
Abby学摄影(第一季)
Abby学摄影(第一季)《Abby学摄影》是咔图摄影教育中心重磅推出的免费的摄影视频教程,实用且诙... -
轻量级saas平台如何使用Django快速搭建_第
轻量级saas平台如何使用Django快速搭建_第项目涵盖技术和知识点概览: 1. 注册、登录、手机短信、图片验证码、redis超时... -
朗文国际英语教程side by side 免费试听课
朗文国际英语教程side by side 免费试听课适合人群:适合上小学或者初中一年级的孩子。 教材简介: 全套四册教材共涵...
mongodb使用group by:
我们比较熟悉的group by 的sql语句select key from table groupby key,而mongoDB没提供SQL那样通过Group By就轻松实现数据库的分组功能,我们通过接口来实现的
db.collection.group({ key, reduce, initial[, keyf] [, cond] [, finalize] })
1.MonogoDB数据库中添加订单的数据
/* 0 */ { "_id" : ObjectId("552a330e05c27486b9b9b650"), "_class" : "com.mongo.model.Orders", "onumber" : "002", "date" : ISODate("2014-01-03T16:03:00Z"), "cname" : "zcy", "item" : { "quantity" : 1, "price" : 4.0, "pnumber" : "p002" } } /* 1 */ { "_id" : ObjectId("552a331d05c275d8590a550d"), "_class" : "com.mongo.model.Orders", "onumber" : "003", "date" : ISODate("2014-01-04T16:03:00Z"), "cname" : "zcy", "item" : { "quantity" : 10, "price" : 2.0, "pnumber" : "p001" } } /* 2 */ { "_id" : ObjectId("552a333105c2f28194045a72"), "_class" : "com.mongo.model.Orders", "onumber" : "003", "date" : ISODate("2014-01-04T16:03:00Z"), "cname" : "zcy", "item" : { "quantity" : 30, "price" : 4.0, "pnumber" : "p002" } } /* 3 */ { "_id" : ObjectId("552a333f05c2b62c01cff50e"), "_class" : "com.mongo.model.Orders", "onumber" : "004", "date" : ISODate("2014-01-05T16:03:00Z"), "cname" : "zcy", "item" : { "quantity" : 5, "price" : 4.0, "pnumber" : "p002" } }
2.MongoDB实现分组并统计
1)我们要对日期和产品编码进行分组,并计算相同的产品的数量
Sql语句:
Select date, pnumber,sum(quantity) as total from orders,items group by date, pnumber
(少了两张表的关联的条件)
MongoDB: db.orders.group({ key: { date:1,'item.pnumber':1}, initial : {"total":0}, reduce : function Reduce(doc, out) { out.total+=doc.item.quantity } });
结果:
2)实现一天卖出了多少个产品,金额是多少,平均价格是多少
db.orders.group({ key: {date:1}, initial :{"total":0,"money":0}, reduce : function Reduce(doc, out) { out.total+=doc.item.quantity; out.money+=doc.item.quantity*doc.item.price; }, finalize : function Finalize(out) { out.avg=out.money/out.total returnout; } });
结果:
3)keyf的使用
keyf 对日期进行处理并以作为key来进来分组
db.orders.group({ keyf: function (doc){ return{'month':doc.date.getMonth()+1}; }, initial :{"total":0,"money":0}, reduce : function Reduce(doc, out) { out.total+=doc.item.quantity; out.money+=doc.item.quantity*doc.item.price; }, finalize : function Finalize(out) { out.avg=out.money/out.total returnout; } });
结果:
课程教程:mongodb 如何使用group by
上一篇:mongodb插入时间错误
下一篇:没有了