MongoDB can be used to count documents per year, or per month, etc. In traditional SQL, this would be accomplished via a COUNT and “GROUP BY” clause. In MongoDB, this can be accomplished like so:

db.pictures.aggregate(
{
    "$project": {
        "y": {
            "$year": "$picture_datetime.taken",
        },
        "m": {
            "$month": "$picture_datetime.taken",
        },
    }
},
{
    "$group": {
        "_id": {
            "year": "$y",
            "month": "$m"
        },
        count: {
            "$sum": 1
        }
    }
},
{
    $sort: {
        "_id.year": -1,
        "_id.month": -1,
    }
})

This can be used for all sorts of things, including generating heatmaps.

Leave a Reply

Your email address will not be published. Required fields are marked *