how to use “group” in pymongo to group similar rows?

不想你离开。 提交于 2019-12-22 04:07:43

问题


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

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

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.

Thanks,


回答1:


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

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



来源:https://stackoverflow.com/questions/5010624/how-to-use-group-in-pymongo-to-group-similar-rows

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