【问题标题】:Group and Combine Text Fields Using Pymongo使用 Pymongo 对文本字段进行分组和组合
【发布时间】:2021-09-14 09:37:26
【问题描述】:

我有一组用户评论,我正在尝试按用户合并所有评论,以便对它们进行一些 NLP 分析。这感觉应该很容易,但我在 Mongo 处理字符串的方式上遗漏了一些东西。

我的文档如下所示:

{'_id': ObjectId('57e079d3e3874f12ad721f70'),
 'atmosphere': 5,
 'review_id': 63,
 'dedication': 3,
 'orgName': 'Some Organization',
 'enabled': True,
 'accessibility': 3,
 'efficiency': 3,
 'orgId': '57e05e0de3874f121d516616',
 'user': '5809f2c0bc0a53eb49eac583',
 'date': '10/20/15 0:00',
 'quality': 3,
 'orgId_orig': 1098,
 'description': 'Here is some sample text'
}

我试过了:

    agg_result = revs.aggregate( [
       { "$group": { "_id": "$user", "mergedText": { "$mergeObjects": "$description"  } } }
    ])

for i in agg_result:
    print(i)

但是我收到了这个错误:

OperationFailure: $mergeObjects requires object inputs, but input "Here is some sample text" is of type string

我的预期输出是

{
'userId1':{'mergedText':'joined descriptions from this user'},
'userId2':{'mergedText':'this users descriptions'},
'userId3':{'mergedText':'all descriptions from this user'}
}

其中各种用户 ID 是来自“用户”字段的 Mongo ObjectId。

我是 Mongo 的新手,这让我有一段时间了。谢谢。

【问题讨论】:

  • 完成,感谢您让我知道这样做。

标签: mongodb aggregation-framework pymongo


【解决方案1】:

试试这个,合并对象需要对象但是你的描述是字符串,你可以推入数组

agg_result = revs.aggregate( [
       { "$group": { "_id": "$user", "mergedText": { "$push": "$description"  } } }
    ])

for i in agg_result:
    print(i)

【讨论】:

  • 非常感谢。我需要稍微调整一下以格式化输出(我忘记发布您何时回答的示例 - 所以这在我身上),但这回答了问题。我还没有足够的声望来投票,但我确实点击了向上箭头。
  • 谢谢,更新您的问题并通知我
猜你喜欢
  • 1970-01-01
  • 2019-03-20
  • 2019-04-16
  • 2011-06-27
  • 2023-01-12
  • 2021-08-28
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多