PyMongo - 获取用户提及的用户网络的聚合管道

PyMongo - Aggregation pipeline to get user - mentioned user network

我已经在 Mongo 数据库集合中上传了一些推文,我想用 PyMongo 提取以下信息:

即我想知道谁提到了谁,提到了多少次,以建立某种网络。

我使用以下管道获得了最多提及的用户,但我无法同时介绍 user.screen_name:

tweets.aggregate([
    {'$project': {'mentions': '$entities.user_mentions.screen_name', '_id': 0}},
    {'$unwind': '$mentions'},
    {'$group': {'_id': '$mentions', 'count': {'$sum': 1}}}
])

这是文档(推文)的示例,我在其中删除了一些我不感兴趣的字段:

{'_id': ObjectId('604c805b289d1ef5947e1845'),
 'created_at': 'Fri Mar 12 04:36:10 +0000 2021',
 'display_text_range': [0, 140],
 'entities': {'hashtags': [{'indices': [124, 136], 'text': 'mytag'}],
              'symbols': [],
              'urls': [],
              'user_mentions': [{'id': 123,
                                 'id_str': '123',
                                 'indices': [3, 14],
                                 'name': 'user_name',
                                 'screen_name': 'user_screen_name'}]},
 'user': {'id': 456,
          'id_str': '456',
          'name': 'Author Name',
          'screen_name': 'Author Screen Name'}}

{'_id': ObjectId('604c805b289d1ef5947e184x'),
 'created_at': 'Fri Mar 12 04:36:10 +0000 2021',
 'display_text_range': [0, 140],
 'entities': {'hashtags': [{'indices': [124, 136], 'text': 'mytag'}],
              'symbols': [],
              'urls': [],
              'user_mentions': [{'id': 126,
                                 'id_str': '126',
                                 'indices': [3, 14],
                                 'name': 'user_name',
                                 'screen_name': 'user_screen_name'}]},
 'user': {'id': 4567,
          'id_str': '4567',
          'name': 'Other Author Name',
          'screen_name': 'Other Author Screen Name'}}

在这个例子中,我希望是这样的:

{'mentioned': 'user_screen_name',
'author': 'Author Screen Name',
'count': '1'},
{'mentioned': 'user_screen_name',
'author': 'Other Author Screen Name',
'count': '1'},

有人可以帮助我吗?

提前感谢您的帮助!

弗朗西斯卡

db.collection.aggregate([
  {
    "$project": {
      "mentions": "$entities.user_mentions.screen_name",
      "author": "$user.screen_name"
    }
  },
  { "$unwind": "$mentions" },
  {
    "$group": {
      "_id": { aut: "$author", ment: "$mentions" },
      "count": { "$sum": 1 },
      author: { "$first": "$author" },
      mentions: { "$first": "$mentions" }
    }
  },
  {
    "$project": { _id: 0 }
  }
])

工作Mongo playground