需要Mongodb聚合輸出格式的幫助。Mongodb,聚合,如何抑制_id,但保持裏面的內容?
我的數據條目包括的東西是這樣的:
{'parent_id': '133', 'status_id': '209101162445115_1199071210114767', 'author_id': '10209422198664172', 'comment_published': '2016-08-15 08:57:09'}
我需要統計author_ids的出現次數,給定一個匹配PARENT_ID。我這樣做,與骨料:
m = collection.aggregate([{"$match": {"parent_id":"437325203079413_1543639"}},
{ "$group": {"_id": {"author_id": "$author_id"}, "count":{"$sum":1}}},
{"$project": {"_id":1, "count":1}} ]) #this line does not make any difference in the output.
page =[]
for i in m:
page.append(i)
print(page)
輸出看起來是這樣的:
[{'_id': {'author_id': '10155430875324466'}, 'count': 1},
{'_id':{'author_id': '1249853341715138'}, 'count': 2},
{'_id': {'author_id': '10153804689530108'}, 'count': 1}]
我所要的輸出爲以下格式:
[{'author_id': '10155430875324466', 'count': 1},
{'author_id': '1249853341715138', 'count': 2},
{'author_id': '10153804689530108', 'count': 1}]
或者這樣:
[{'10155430875324466', 1},
{'1249853341715138', : 2},
{'10153804689530108', 1}]
我知道一個緩慢的做法在Python中,但我覺得應該有更好的解決方案。是否有可能在聚合查詢本身內完成該操作?任何人都可以建議嗎?
只要改變你的$項目舞臺{ 「$項目」:{ 「AUTHOR_ID」:$ _ ID, 「計數」:1}},你想你的第二個輸出中不是一個有效的JSON.Please更正一下,你要。 –
謝謝。如果我還將該組更改爲直接投影,則此方法有效:{「$ group」:{「_id」:「$ author_id」,「count」:{「$ sum」:1}}} – www123
最後,我需要將輸出存儲在字典中,如第二個輸出。但是如果我能得到第一個輸出的格式,我可以將它轉換爲Python中的字典。我們不能直接從mongodb查詢獲得第二種格式的輸出,對嗎? – www123