sql to mongodb translation

三世轮回 提交于 2019-12-11 09:37:11

问题


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

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

'$' This is what I do using sql:

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

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

Thank you very much!


回答1:


Setting up test data with:

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')})

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
}



回答2:


Check the mongodb Aggregation

db.colection.group(
  {key: { id:true},
  reduce: function(obj,prev) { prev.sum += 1; },
  initial: { sum: 0 }
});

After you get the result, sort it by sum.



来源:https://stackoverflow.com/questions/12189273/sql-to-mongodb-translation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!