0
我有以下數據。我想運行查詢按類別和月份對結果進行分組並返回總計。mongodb組在月份部分日期
第一個期望的輸出是月份名稱的嵌套數組,其總計12個月的總計按類別。數據中不存在的月份仍將返回,但總數爲0。
{"category":"Auto","month":{"Jan":9.12,"Feb":9.12,"Mar":0,...}},
{"category":"Fees","month":{..."Apr":0,"May":4.56,"Jun":0,...}},
{"category":"Travel","month":{..."Oct":0,"Nov":4.56,"Dec":0}}
第二所需的輸出是沒有嵌套個月的數組...
{"category":"Auto","Jan":4.56,"Feb":4.56,"Mar":0,...},
{"category":"Fees",..."Apr":0,"May":4.56,"Jun":0,...},
{"category":"Travel",..."Oct":0,"Nov":0,"Dec":4.56,}
如何才能將這些結果與MongoDB的查詢?這裏是樣本輸入數據:
{
"_id" : ObjectId("583f6e6d14c8042dd7c153f1"),
"transid" : 1,
"category": "Auto",
"postdate" : ISODate("2016-01-28T05:00:00.000Z"),
"total" : 4.56 }
{
"_id" : ObjectId("583f6e6d14c8042dd7c153f2"),
"transid" : 5,
"category": "Auto",
"postdate" : ISODate("2016-01-31T05:00:00.000Z"),
"total" : 4.56 }
{
"_id" : ObjectId("583f6e6d14c8042dd7c153f3"),
"transid" : 3,
"category": "Auto",
"postdate" : ISODate("2016-02-28T05:00:00.000Z"),
"total" : 4.56 }
{
"_id" : ObjectId("583f6e6d14c8042dd7c153f4"),
"transid" : 2,
"category": "Auto",
"postdate" : ISODate("2016-02-31T05:00:00.000Z"),
"total" : 4.56 }
{
"_id" : ObjectId("583f6e6d14c8042dd7c153f5"),
"transid" : 6,
"category": "Fees",
"postdate" : ISODate("2016-05-16T05:00:00.000Z"),
"total" : 4.56 }
{
"_id" : ObjectId("583f6e6d14c8042dd7c153f6"),
"transid" : 7,
"category": "Travel",
"postdate" : ISODate("2016-11-13T05:00:00.000Z"),
"total" : 4.56 }
我是新來的MongoDB和來自SQL背景,所以我覺得我已經在SQL方面一直在思考這一切。
以下是我迄今爲止基於讀取mongodb文檔並嘗試翻譯「sql think」而嘗試的內容。我基本上試圖過濾到指定的一年(在這種情況下,2016年)。然後我按類別和日期分組。在最後一步,我計劃使用項目和$ cond關鍵字在月份「subaggregate」,方法是指定每個月的開始日期和結束日期,然後將月份名稱指定爲Jan,Feb等...我有語法錯誤我不知道這是否正確或最好的方法。
db.transactions.aggregate(
[
{ $match: { "postdate": {$gte: new Date("2016-01-01")}} },
{ $group: { _id: {"category":"$category","postdate":"$postdate"} , "total": { $sum: "$debit" } } },
{ $project: {"_id":0,"category":"$_id.category",
"month":{$cond: {
$and:
[
{ $gte: ["$_id.postdate", new Date("2016-01-01")] },
{ $lt: ["$_id.postdate", new Date("2016-02-01")] },
]
},"Jan":"$sum"}
//repeat for all other 11 months...
}}
]
)
我發現了一個解決方案,可以讓我接近我期望的第一個場景的輸出,但它需要進行一些調整,因爲我無法在幾個月內顯示出來。我會繼續玩下去,但它可能會讓某人走上正軌。我發現這個解決方案在另一個帖子在這裏:[link] http://stackoverflow.com/questions/25843255/mongodb-aggregate-count-on-multiple-fields-simultaneously –
這是我到目前爲止:'db.transactions .aggregate {[$ match:{「postdate」:{$ gte:new Date(「2016-01-01」)}}}, {「$ group」:{ 「_id」:{ 「category 「:」$ category「, 」month「:{」$ month「:」$ postdate「} }, 」total「:{」$ sum「:」$ total「} }},」$「組「:{ 」_id「:」$ _id.category「, 」month「:{」$ push「:{」month「:」$ month「,」total「:」$ total「}} }} ') –