Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrating to MongoDB: how to query GROUP BY + WHERE

I have a MYSQL table with records of people's names and the time of arrival expresed as a number. Think of it as a marathon. I want to know how many people arrived into a certain gap of time who where named the same, so:

SELECT name, COUNT(*) FROM mydb.mytable
WHERE Time>=100 AND Time<=1000
GROUP BY name

And as results I get:

Susan, 1
John, 4
Frederick, 1
Paul, 2

I'm migrating to MongoDB now, and using Python to code (so I'm asking for Pymongo help). I tried looking for information about the GROUP BY equivalent (even when I have read that NoSQL databases are worse at this kind of operation than the SQL ones), but since they released the new agreggate API, I hjaven't been able to find a simple example like this solved with the group method, the Map-Reduce method or the brand new agreggate API.

Any help?

like image 279
Roman Rdgz Avatar asked Jul 31 '13 10:07

Roman Rdgz


1 Answers

There are examples of this all over the documentation, Google and this site.

Some references:

  • http://api.mongodb.org/python/current/examples/aggregation.html
  • http://docs.mongodb.org/manual/reference/aggregation/group/
  • http://docs.mongodb.org/manual/reference/aggregation/sum/

And for some code:

self.db.aggregate(
    # Lets find our records
    {"$match":{"Time":{"$gte":100,"$lte":1000}}}, 

    # Now lets group on the name counting how many grouped documents we have
    {"$group":{"_id":"$name", "sum":{"$sum":1}}} 
)
like image 174
Sammaye Avatar answered Oct 23 '22 16:10

Sammaye