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

通过使用Mongo Group功能,您可以执行相同的查询。示例如下。

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 回答