注意:我使用燒瓶/pymongo
我如何重新排列我的資料以將它們全部輸出到一個用逗號分隔的單個物件中。(例如,見帖子末尾)。
我有一個包含與此類似的資料的集合,我需要輸出所有次數,例如在這里,那個三明治在像這樣的集合中 Sandwiches: 13 :
{
"id":"J6qWt6XIUmIGFHX5rQJA-w",
"categories":[
{
"alias":"sandwiches",
"title":"Sandwiches"
}
]
}
因此,對于第一個請求:
restos.aggregate([{$unwind:"$categories"},
{$group:{_id:'$categories.title', count:{$sum:1}}},
{$project:{ type:"$_id", count: 1,_id:0}}])
我實作了這樣的輸出:
{ "count" : 3, "type" : "Sandwiches" }
但我想要的是型別作為鍵和計數作為值,如下所示: { "Sandwiches" : 3 }
我能夠“部分使其適用于該命令,但這并不是我真正想要的格式:
.aggregate([{'$unwind': '$categories'},{'$group': {'_id': '$categories.title','count':{'$sum':
1}}},{'$project': {'type': '$_id', 'count': 1, '_id': 0}}, {'$replaceRoot': {'newRoot':
{'$arrayToObject': [[{'k': '$type', 'v': '$count'}]]}}}]))
輸出是:
{
"restaurants": [
{
"Polish": 1
},
{
"Salad": 3
},
{
"Convenience Stores": 1
},
{
"British": 2
}]}
但我想要的輸出是這樣的,它沒有陣列,資料只包含在 1 個物件中:
{
"restaurants":{
Sandwiches: 13,
pizza: 15,
...
}
對于串列的事情,我開始意識到我使用了flask,當我回傳我的jsonify 物件時,我放了'restaurants': list(db.restaurants.aggregate([
但是當我洗掉它時,我收到這個錯誤:TypeError: Object of type CommandCursor is not JSON serializable
知道如何做到這一點嗎?多謝 :)
uj5u.com熱心網友回復:
如果你能得到如下資料。
{ "count" : 13, "type" : "Sandwiches" }
你可以這樣做:
data = [{ "count" : 13, "type" : "Sandwiches" }, { "count" : 15, "type" : "Pizza" }]
output = {}
p = {}
for d in data: # read each item in the list
p.update({d['type']: d['count']}) # build a p dict with type key
output.update({'restaurants': p}) # build an output dict with restaurants key
print(output)
# {'restaurants': {'Sandwiches': 13, 'Pizza': 15}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/343226.html
上一篇:將函式應用于csv檔案中的每一行
