SQL统计转MongoDB统计,请问这种统计如何转换?

BeerGates 2017-07-14 07:48:13
请问如何将SQL方式的GROUP BY转到MongoDB?

SQL

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[test](
[_id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
[Amount] [decimal](18, 4) NOT NULL,
[Addr] [varchar](50) NOT NULL,
[Amount2] [decimal](18, 4) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT test(Name,Amount,Addr,Amount2) VALUES('A1',11,'CN',0.1)
INSERT test(Name,Amount,Addr,Amount2) VALUES('A1',12,'US',0.2)
INSERT test(Name,Amount,Addr,Amount2) VALUES('A1',13,'US',0.3)
INSERT test(Name,Amount,Addr,Amount2) VALUES('A2',14,'CN',0.4)
INSERT test(Name,Amount,Addr,Amount2) VALUES('A2',15,'US',0.5)
SELECT Name,Addr,SUM(Amount),SUM(Amount2) FROM test GROUP BY Name,Addr



MongoDB

db.createCollection("test")
db.test.remove({"_id":{"$ne":"10"}})
db.test.insert({Name:"A1",Amount:11,Addr:"CN",Amount2:0.1})
db.test.insert({Name:"A1",Amount:12,Addr:"US",Amount2:0.2})
db.test.insert({Name:"A1",Amount:13,Addr:"US",Amount2:0.3})
db.test.insert({Name:"A2",Amount:14,Addr:"CN",Amount2:0.4})
db.test.insert({Name:"A2",Amount:15,Addr:"US",Amount2:0.5})
...全文
218 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
SYBN 2020-04-07
  • 打赏
  • 举报
回复
试试: https://blog.csdn.net/sl543001/article/details/102823055
BeerGates 2017-07-14
  • 打赏
  • 举报
回复
引用 1 楼 my_bot 的回复:
没人回答我来吧 db.test.aggregate() .group({ _id: {"Name":"$Name","Addr":"$Addr"}, Amount: { $sum: "$Amount" },Amount2:{$sum: {"$Amount2"}} })
谢谢啊 之前搞错了,写_id:["$name","addr"],网上搜索不到
my_bot 2017-07-14
  • 打赏
  • 举报
回复
没人回答我来吧 db.test.aggregate() .group({ _id: {"Name":"$Name","Addr":"$Addr"}, Amount: { $sum: "$Amount" },Amount2:{$sum: {"$Amount2"}} })

1,747

社区成员

发帖
与我相关
我的任务
社区描述
MongoDB相关内容讨论区
社区管理员
  • MongoDB社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧