MongoDB聚合按不同对分组

2024-10-04 11:29:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用PyMongo驱动程序按无序的不同字段对(sender和{})对特定集合中的记录进行分组。 例如,对(发送方字段_值、接收方字段_值)(接收方字段值、发送方字段值)被视为相等。在

我的聚合管道

groups = base.flow.records.aggregate([
    {'$match': {'$or': [
                {'sender': _id},
                {'recipient': _id}
            ]
        }
    },
    {'$group': {
            '_id': {
                'sender': '$sender',
                'recipient': '$recipient',
            }, 
            'data_id': {
                '$max': '$_id'
            }
        }
    },            
    {'$limit': 20}
])

应用于数据

^{pr2}$

产生以下结果

{'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')}
  ]
}

合适的管道是什么?在


Tags: iddata管道记录驱动程序okresultsender
1条回答
网友
1楼 · 发布于 2024-10-04 11:29:15

实现不同的对分组的诀窍是将相同的“东西”传递给$group\u id。我将使用普通的比较方法(你可以想出更适合你情况的不同方法——如果你的发送者和接收者不能直接进行比较,我的解决方案不起作用):

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

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

^{pr2}$

相关问题 更多 >