我遇到了一些問題,我不知道應該在 MongoDB 檔案中搜索什么關鍵字。
所以問題是,我現在有一個用戶進行的交易記錄串列,例如如下。
[
{
"_id": Some_Mongo_ID,
"invoiceId": "ABCDEFG",
"username": "randomUser"
"amount": 80,
"createdAt": "2022-04-18T06:59:07.836Z"
},
{
"_id": Some_Mongo_ID,
"invoiceId": "ABCDEFG",
"username": "randomUser"
"amount": 70,
"createdAt": "2022-04-19T06:59:07.836Z"
},
{
"_id": Some_Mongo_ID,
"invoiceId": "ABCDEFG",
"username": "randomUser"
"amount": 55,
"createdAt": "2022-05-18T06:59:07.836Z"
},
...
]
在我正在使用的儀表板應用程式中,有一個折線圖。為了提供折線圖,我需要以某種方式對我擁有的交易的原始資料進行查詢/聚合,并將它們分組到一個物件陣列中,其中包含該月的月份和總支出。
[
{
"period": "2022-04",
"totalSpending": 900
},
{
"period": "2022-05",
"totalSpending": 2000
},
{
"period": "2022-06",
"totalSpending": 367
},
...
]
技術上是否可以查詢/聚合我擁有的資料并將它們按月分組到一個陣列中,如上所示?
如果提供任何資訊將不勝感激。謝謝
uj5u.com熱心網友回復:
操場
db.collection.aggregate([
{
"$group": {
"_id": {
month: { //Group by Month
"$month": "$createdAt"
},
year: { //Group by Year
"$year": "$createdAt"
}
},
"totalSpending": { //Accumulate sum for the group
$sum: "$amount"
}
}
},
{
"$project": { //You can ignore this if the group format is ok
"totalSpending": 1,
"period": { //To form the expected string
"$concat": [
{
$toString: "$_id.year"
},
"-",
{
$toString: "$_id.month"
}
]
},
"_id": 0
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/477715.html
標籤:javascript json mongodb 猫鼬 聚合框架
