mongodb - 使用 Pymongo 对文本字段进行分组和组合
问题描述
我有一组用户评论,我正在尝试按用户组合所有评论,以便我可以对它们进行一些 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 的新手,这已经让我绊倒了一段时间。谢谢你。
解决方案
试试这个,合并对象需要对象但是你的描述是你可以推入数组的字符串
agg_result = revs.aggregate( [
{ "$group": { "_id": "$user", "mergedText": { "$push": "$description" } } }
])
for i in agg_result:
print(i)