backlunp
backlunp

Reputation: 75

Counting and aggregation based on date fields in MongoDB

I am building an application using Python and MongoDB. I would like to add a new collection that has some statistics about the data I've been collecting. I have been able to get it to function using queries, but it seems like I should be able to offload this work to the Aggregation Framework.

Here is an example of what my documents look like:

foundFile = {
    "_id": ObjectID("5b81abb7bc1e7479981a042f")
    "fileType": ".ico",
    "timeStamp": 1535659134,  # unix timestamp
    "size": 929191            # size in bytes
}

I would like to know 2 things:

Is this something the Aggregate Framework is good for? Or should I stick to queries?

Thanks for reading.

UPDATE

For anyone who is getting started with the Aggregation Framework like myself, there is a tab in MongoDB Compass on the collection page that helps you build aggregations and export them to your desired language which I, for one, found extremely helpful in figuring out why my query didn't work.

Upvotes: 2

Views: 61

Answers (1)

s7vr
s7vr

Reputation: 75964

You can use below aggregation.

db.colname.aggregate([
  {"$match":{"timeStamp":{"$gte":time24hoursago,"$lte":currenttime}}},
  {"$group":{
    "_id":"$fileType",
    "ucount":{"$sum":1},
    "asize":{"$sum":"$size"}
  }}
])

Upvotes: 2

Related Questions