【问题标题】:MongoDB aggregation - grouping by distinct pairsMongoDB 聚合 - 按不同对分组
【发布时间】:2014-05-10 17:00:49
【问题描述】:

我需要使用 PyMongo 驱动程序通过无序的不同字段对(senderrecipient)对来自某个集合的记录进行分组。 例如对 (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


【解决方案1】:

实现不同对分组的诀窍是通过向 $group _id 传递任何一种情况下的相同“事物”。我将使用常规比较来做到这一点(您可以提出更适合您情况的不同内容 - 如果您的发件人和收件人不能直接比较,我的解决方案将不起作用):

{$project : {
    "_id" : 1,
    "groupId" : {"$cond" : [{"$gt" : ['$sender', '$recipient']}, {big : "$sender", small : "$recipient"}, {big : "$recipient", small : "$sender"}]}
}},
{$group: {
    '_id': "$groupId",
    'data_id': {
        '$max': '$_id'
    }
}}

完整的聚合管道如下所示:

{$match : {
    '$or': [{'sender': userId},{'recipient': userId}]
}},
{$project : {
    "_id" : 1,
    "groupId" : {"$cond" : [{"$gt" : ['$sender', '$recipient']}, {big : "$sender", small : "$recipient"}, {big : "$recipient", small : "$sender"}]}
}},
{$group: {
    '_id': "$groupId",
    'data_id': {
        '$max': '$_id'
    }
}},
{$limit: 20}

【讨论】:

  • 这很聪明。谢谢。
猜你喜欢
  • 2016-07-03
  • 2015-03-28
  • 2021-05-19
  • 2013-11-25
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多