迁移到MongoDB:如何查询GROUP BY + WHERE [英] Migrating to MongoDB: how to query GROUP BY + WHERE
问题描述
我有一个MYSQL表,上面记录着人们的姓名,到达时间用数字表示.认为这是一场马拉松比赛.我想知道有多少人在某个时间间隔内到达了相同的名字,所以:
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
结果我得到了:
Susan, 1
John, 4
Frederick, 1
Paul, 2
我现在正在迁移到MongoDB,并使用Python进行编码(因此,我需要Pymongo帮助).我尝试查找有关GROUP BY的信息(即使我已经读到NoSQL数据库在这种操作上比SQL还要差),但是由于它们发布了新的Agreggate API,所以我一直无法找到这样的简单示例可以通过group方法,Map-Reduce方法或全新的agreggate API解决.
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.
有帮助吗?
推荐答案
在文档,Google和此网站上都有一些示例.
There are examples of this all over the documentation, Google and this site.
一些参考文献:
- 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 /
- 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/
对于某些代码:
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}}}
)
这篇关于迁移到MongoDB:如何查询GROUP BY + WHERE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!