【发布时间】:2014-05-10 17:00:49
【问题描述】:
我需要使用 PyMongo 驱动程序通过无序的不同字段对(sender 和 recipient)对来自某个集合的记录进行分组。
例如对 (sender_field_value, recipient_field_value) 和 (recipient_field_value, sender_field_value) 被认为是相等的。
我的聚合管道
groups = base.flow.records.aggregate([
{'$match': {'$or': [
{'sender': _id},
{'recipient': _id}
]
}
},
{'$group': {
'_id': {
'sender': '$sender',
'recipient': '$recipient',
},
'data_id': {
'$max': '$_id'
}
}
},
{'$limit': 20}
])
应用于数据
{ "_id" : ObjectId("533950ca9c3b6222569520c2"), "recipient" : ObjectId("533950ca9c3b6222569520c1"), "sender" : ObjectId("533950ca9c3b6222569520c0") }
{ "_id" : ObjectId("533950ca9c3b6222569520c4"), "recipient" : ObjectId("533950ca9c3b6222569520c0"), "sender" : ObjectId("533950ca9c3b6222569520c1") }
产生以下内容
{'ok': 1.0,
'result': [
{'_id': {'recipient': ObjectId('533950ca9c3b6222569520c0'), 'sender': ObjectId('533950ca9c3b6222569520c1')},
'data_id': ObjectId('533950ca9c3b6222569520c4')},
{'_id': {'recipient': ObjectId('533950ca9c3b6222569520c1'), 'sender': ObjectId('533950ca9c3b6222569520c0')},
'data_id': ObjectId('533950ca9c3b6222569520c2')}
]
}
但想要的结果只是
{'ok': 1.0,
'result': [
{'_id': {'recipient': ObjectId('533950ca9c3b6222569520c0'), 'sender': ObjectId('533950ca9c3b6222569520c1')},
'data_id': ObjectId('533950ca9c3b6222569520c4')}
]
}
什么是合适的管道?
【问题讨论】:
-
也许显示应该减少到这个结果的数据。
-
@NeilLunn 已更新,但我想它太小了,无法提供帮助
标签: python mongodb python-3.x pymongo aggregation-framework