2012-11-20 52 views
2

我是pymongo/mongodb的新手,现在我面临挑战。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 

] 

回答

5

如果您在使用MongoDB的2.1+可以使用aggregation framework对于这种类型的查询:

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 }} 
]) 
+0

谢谢许多。我正在运行2.0.4版本,所以我想我必须使用map reduce。考虑升级到2.1.x,但读取它的unstable ... – terjeto

+0

@terjeto像2.1这样的奇数编号的发布版本是不稳定的开发版本,但2.2.1已经发布并且稳定。那是你想要的。 – JohnnyHK