我在mongodb中有一个数据:
{'word': 'good', 'info': [{'tbl_id': 'd1', 'term_freq': 2}, {'tbl_id': 'd2', 'term_freq': 56}, {'tbl_id': 'd3', 'term_freq': 3}]}
{'word': 'spark', 'info': [{'tbl_id': 'd1', 'term_freq': 6}, {'tbl_id': 'd3', 'term_freq': 11}, {'tbl_id': 'd4', 'term_freq': 10}]}
{'word': 'good', 'info': [{'tbl_id': 'd4', 'term_freq': 12}, {'tbl_id': 'd5', 'term_freq': 8}, {'tbl_id': 'd8', 'term_freq': 7}]}
{'word': 'spark', 'info': [{'tbl_id': 'd5', 'term_freq': 6}, {'tbl_id': 'd6', 'term_freq': 11}, {'tbl_id': 'd7', 'term_freq': 10}]}
我想减少同一个词,信息应该是一个集成列表。怎么办?
预期产出:
{'word': 'good',
'info': [{'tbl_id': 'd1', 'term_freq': 2}, {'tbl_id': 'd2', 'term_freq': 56}, {'tbl_id': 'd3', 'term_freq': 3},
{'tbl_id': 'd4', 'term_freq': 12}, {'tbl_id': 'd5', 'term_freq': 8}, {'tbl_id': 'd8', 'term_freq': 7}]}
{'word': 'spark',
'info': [{'tbl_id': 'd1', 'term_freq': 6}, {'tbl_id': 'd3', 'term_freq': 11}, {'tbl_id': 'd4', 'term_freq': 10},
{'tbl_id': 'd5', 'term_freq': 6}, {'tbl_id': 'd6', 'term_freq': 11}, {'tbl_id': 'd7', 'term_freq': 10}]}
下面的聚合查询将为您提供集成的信息列表,按单词分组
db.collection.aggregate([{'$unwind':'$info'},{'$group':{'_id':'$word','info':{'$push':'$info'}}}])
输出:
{
"_id" : "spark",
"info" : [
{
"tbl_id" : "d1",
"term_freq" : 6
},
{
"tbl_id" : "d3",
"term_freq" : 11
},
{
"tbl_id" : "d4",
"term_freq" : 10
},
{
"tbl_id" : "d5",
"term_freq" : 6
},
{
"tbl_id" : "d6",
"term_freq" : 11
},
{
"tbl_id" : "d7",
"term_freq" : 10
}
]
}
{
"_id" : "good",
"info" : [
{
"tbl_id" : "d1",
"term_freq" : 2
},
{
"tbl_id" : "d2",
"term_freq" : 56
},
{
"tbl_id" : "d3",
"term_freq" : 3
},
{
"tbl_id" : "d4",
"term_freq" : 12
},
{
"tbl_id" : "d5",
"term_freq" : 8
},
{
"tbl_id" : "d8",
"term_freq" : 7
}
]
}