sql到mongodb的翻译 [英] sql to mongodb translation

查看:212
本文介绍了sql到mongodb的翻译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何从sql到mongoDB进行以下转换:

I wonder how we can do the below translation from sql to mongoDB:

假设表格具有以下结构:

Assume the table has below structure:

table
=====
-----
##id contribution         time

1            300                  Jan 2, 1990

2            1000                 March 3, 1991


我想找到ID的排名列表,按其贡献数的降序排列.


And I want to find a ranking list of ids in the descending orders of their number of contributions.

'$'这是我使用sql所做的:

'$' This is what I do using sql:

select id, count(*) c from table group by id order by c desc;

如何使用count(),order()和group()将此复杂的sql转换为mongoDB?

How can I translate this complex sql into mongoDB using count(), order() and group()?

非常感谢!

推荐答案

使用以下方法设置测试数据:

Setting up test data with:

db.donors.insert({donorID:1,贡献:300,日期:ISODate('1990-01-02')}) db.donors.insert({donorID:2,贡献:1000,日期:ISODate('1991-03-03')}) db.donors.insert({donorID:1,贡献度:900,日期:ISODate('1992-01-02')})

db.donors.insert({donorID:1,contribution:300,date:ISODate('1990-01-02')}) db.donors.insert({donorID:2,contribution:1000,date:ISODate('1991-03-03')}) db.donors.insert({donorID:1,contribution:900,date:ISODate('1992-01-02')})

您可以在MongoDB 2.2中使用新的聚合框架:

You can use the new Aggregation Framework in MongoDB 2.2:

db.donors.aggregate(
    { $group: {
        _id: "$donorID",
        total:   { $sum: "$contribution" },         
        donations: { $sum: 1 }
    }},
    { $sort: {
        donations: -1
    }}
)

要产生所需的结果,请执行以下操作:

To produce the desired result:

{
    "result" : [
        {
            "_id" : 1,
            "total" : 1200,
            "donations" : 2
        },
        {
            "_id" : 2,
            "total" : 1000,
            "donations" : 1
        }
    ],
    "ok" : 1
}

这篇关于sql到mongodb的翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆