我是pymongo/mongodb的新手,现在我遇到了挑战。
我在 mongodb (v 2.04) 中存储了以下结构。
{
"t": <timestamp>,
"d": {
"uid": <string>,
"action": <string>
}
}
此结构跟踪用户操作,并且与我的原始结构相比,复杂性略有降低。数据非常庞大,查询将具有限制日期跨度以减少结果。
我希望能够创建一个在特定时间跨度内执行最多操作的用户表。
桌子:
Rank Uid #num actions
1 5 235
2 237 234
3 574 229
到目前为止,我只了解了查询的零碎内容:
query = {"t": {"$lte": end_utc, "$gte": start_utc}}
db.actions.find(query).distinct("d.uid")
这将简单地生成一个唯一 uid 的列表。如何查询(使用 pymongo)以获取列表,例如:
[
{
"actions": 100,
"uid": 273
},
{
"actions": 99",
"uid": 632
}..n sorted on actions descending
]
如果您使用的是MongoDB 2.1+,则可以将聚合框架用于此类查询:
db.actions.aggregate([
# Filter the docs to just those within the specified timerange
{"$match": {"t": {"$lte": end_utc, "$gte": start_utc}}},
# Group the docs on d.uid, assembling a count of action docs with each value
{"$group": {"_id": "$d.uid", "actions": {"$sum": 1}}},
# Sort by actions, descending
{"$sort": { "actions": -1 }}
])