Question

I have a collection in my MongoDB with the following structure:

{
        "_id" : "17812",
        "date" : ISODate("2014-03-26T18:48:20Z"),
        "text" : "............."
}

I want to use pyMongo and return in a list the number of documents each month from a certain date until now. The way I am doing it now, is to retrieve all the documents without filters and then create the list in Python. I am not sure, but do you know if I can do this one only with pymongo query?

Was it helpful?

Solution

So getting the counts for a whole month you can use the date operators in the aggregation pipeline. You can also combine with a $match in order to get the range of dates you want.

var start = new Date("2013-06-01");
var today = new Date();

db.collection.aggregate([
    { "$match": {
        "date": { "$gte": start, "$lt": today }
    }},
    { "$group": {
        "_id": {
           "year": { "$year": "$date" },
           "month": { "$month": "$date" },
        },
        "count": { "$sum": 1 }
    }}
])

OTHER TIPS

Take a look at the aggregation framework in MongoDB which is ideal for this kind of task. It can be used from pyMongo with the aggregate method on a collection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top