0

I have a collection "posts" in Mongo that has a date column, lets call it "posted_on" and I would like to get a list of the month/year combos that exist in this column.

If this was an SQL do I would do something like

SELECT MONTH(posted_on), YEAR(posted_on), count(*) 
FROM posts GROUP BY YEAR(posted_on), MONTH(posted_on) 

which would get me a list of years and months.

Preferably I would like a query in mongoose, however I can convert a mongo query easy enough.

4

1 に答える 1

3

By using Mongo Group function you can do the same query. The example is as follows.

db.posts.group(
{
    keyf: function(doc) {
        return {
            month : doc.posted_on.getMonth(), 
            year : doc.posted_on.getFullYear()
        };
    },
    reduce: function(obj,prev) {
        prev.count++
    },
    initial: {count:0}
});
于 2012-06-27T07:31:31.743 に答える