Migrating to MongoDB: how to query GROUP BY + WHERE

早过忘川 提交于 2019-12-18 15:54:06

问题


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?


回答1:


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}}} 
)


来源:https://stackoverflow.com/questions/17967586/migrating-to-mongodb-how-to-query-group-by-where

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!