2017-03-13 31 views
0

我創建了一個見解儀表板,我有一些很多的數據和存儲計數,但我需要將它合併到一個文檔中。 (umm很難用文字解釋),例如MongoDB - 多個查詢和單個文檔結果

網站集:

{ 
Name: "..." 
ApiKey: "SomeUnique1" 
Insights: 
{ 
    sumOfData: 5, 
    anotherSum: 14 
} 
}, 
{ 
    Name: "..." 
    ApiKey: "SomeUnique2" 
    Insights: 
    { 
     sumOfData: 5, 
     anotherSum: 1 
    } 
    },... 

我想要檢索下一個下列數據:

{ 
    ChartDashboard: "Usage" 
    Insights: 
    { 
     sumOfData: 10, 
     anotherSum: 15 
    } 
    } 

我讀了$和運營商可以與一些ApiKey的屬性檢索,但MongoDB中有任何操作,使這個?

+1

使用聚集。看看[$組](https://docs.mongodb.com/manual/reference/operator/aggregation/group/)運營商 – felix

+0

嗯,是的!,這是非常有用的 –

回答

1

您可以使用聚合框架。一個實例是以下情況:

db.collection.aggregate([ 
{ '$group': 
    { 
    _id:null, 
    'ChartDashboard':'Usage', 
    'sumOfData':{$sum:'$Insights.sumOfData'}, 
    'anotherSum':{$sum:'$Insights.sumOfData'} 
    } 
} 
]) 

和的,其結果將是:此

{ 
    '_id' : null, 
    'ChartDashboard' : 'Usage', 
    'sumOfData' : 10, 
    'anotherSum' : 15 
}