如何使用“组"在pymongo中分组相似的行? [英] how to use "group" in pymongo to group similar rows?

查看:75
本文介绍了如何使用“组"在pymongo中分组相似的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对mongodb/pymongo非常陌生.我已成功将数据导入mongo,并希望使用group函数将相似的行分组在一起.例如,如果我的数据集如下所示:

I am very new to mongodb/pymongo. I have successfully imported my data into mongo and would like to use the group function to group similar row together. For example, if my data set looks like this:

data = [{uid: 1 , event: 'a' , time: 1} , 
        {uid: 1 , event: 'b' , time: 2} ,
        {uid: 2 , event: 'c' , time: 2} ,
        {uid: 3 , event: 'd' , time: 4}
       ]

如何使用分组功能根据uid字段对以上行进行分组,以使输出如下所示?

How do I use the group function to group the above rows according to the uid field such that the output is as follows?

 { {uid: 1} : [{uid: 1 , event: 'a' , time: 1} , {uid: 1 , event: 'b' , time: 2} ],
   {uid: 2} : [{uid: 2 , event: 'c' , time: 2} ],
   {uid: 3} : [{uid: 3 , event: 'd' , time: 4} ] }

我在 http://www.mongodb.org/display/DOCS/上通读了示例聚合.但是,在我看来,这些示例总是聚合为单个数字或对象.

I read through the examples at http://www.mongodb.org/display/DOCS/Aggregation. However, it seems to me that those example always aggregate into a single number or object.

谢谢

推荐答案

您不需要使用reduce函数实际上 reduce 任何东西.例如:

You needn't use the reduce function to actually reduce anything. For example:

>>> coll.insert(dict(uid=1,event='a',time=1))
ObjectId('4d5b91d558839f06a8000000')
>>> coll.insert(dict(uid=1,event='b',time=2))
ObjectId('4d5b91e558839f06a8000001')
>>> coll.insert(dict(uid=2,event='c',time=2))
ObjectId('4d5b91f358839f06a8000002')
>>> coll.insert(dict(uid=3,event='d',time=4))
ObjectId('4d5b91fd58839f06a8000003')
>>> result = coll.group(['uid'], None,
                        {'list': []}, # initial
                        'function(obj, prev) {prev.list.push(obj)}') # reducer
>>> len(result) # will show three groups
3
>>> int(result[0]['uid'])
1
>>> result[0]['list']
[{u'event': u'a', u'_id': ObjectId('4d5b...0000'), u'uid': 1, u'time': 1},
 {u'event': u'b', u'_id': ObjectId('4d5b...0001'), u'uid': 1, u'time': 2}]
>>> int(result[1]['uid'])
2
>>> result[1]['list']
[{u'event': u'c', u'_id': ObjectId('4d5b...0002'), u'uid': 2, u'time': 2}]
>>> int(result[2]['uid'])
3
>>> result[2]['list']
[{u'event': u'd', u'_id': ObjectId('4d5b...0003'), u'uid': 3, u'time': 4}]

为了缩短可读性,我在上面的清单中缩短了对象ID.

I've shortened the object IDs in the above listing to improve readability.

这篇关于如何使用“组"在pymongo中分组相似的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆