您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關mongodb使用group by的案例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
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的案例分析就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。