sql to mongodb translation

2019-08-12 15:51发布

问题:

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.