我有一些資料看起來像這樣:
{'Type':'A',
'Attributes':[
{'Date':'2021-10-02', 'Value':5},
{'Date':'2021-09-30', 'Value':1},
{'Date':'2021-09-25', 'Value':13}
]
},
{'Type':'B',
'Attributes':[
{'Date':'2021-10-01', 'Value':36},
{'Date':'2021-09-15', 'Value':14},
{'Date':'2021-09-10', 'Value':18}
]
}
我想為每個檔案查詢具有最新日期的檔案。有了上面的資料,所需的結果將是:
{'Type':'A', 'Date':'2021-10-02', 'Value':5}
{'Type':'B', 'Date':'2021-10-01', 'Value':36}
我設法找到了一些查詢來查找所有子檔案,只有全域最大值。但是我沒有找到每個檔案的最大值。
非常感謝你的幫助
uj5u.com熱心網友回復:
將日期存盤為字串通常被認為是不好的做法。建議您將日期欄位更改為日期型別。幸運的是,您使用的是 ISO 日期格式,因此可以節省一些精力。
您可以在聚合管道中執行此操作:
- 用于
$max找出最大日期 - 用于
$filter過濾Attributes陣列以僅包含最新元素 $unwind陣列$project到您的預期輸出
這是Mongo 游樂場供您參考。
uj5u.com熱心網友回復:
這僅保留 1 個來自 Attributes 的成員,即具有最大日期的成員。如果您想保留多個成員,請使用 @ray 解決方案,該解決方案保留所有具有最大日期的成員。
*mongoplayground 可能會丟失檔案中欄位的順序,如果您看到錯誤的結果,請在您的驅動程式上測驗它,這是 mongoplayground 工具的錯誤
Query1(本地方式)
測驗代碼在這里
aggregate(
[{"$project":
{"maxDateValue":
{"$max":
{"$map":
{"input": "$Attributes",
"in": {"Date": "$$this.Date", "Value": "$$this.Value"}}}},
"Type": 1}},
{"$project":
{"Date": "$maxDateValue.Date", "Value": "$maxDateValue.Value"}}])
Query2(展開方式)
測驗代碼在這里
aggregate(
[{"$unwind": {"path": "$Attributes"}},
{"$group":
{"_id": "$Type",
"maxDate":
{"$max":
{"Date": "$Attributes.Date", "Value": "$Attributes.Value"}}}},
{"$project":
{"_id": 0,
"Type": "$_id",
"Date": "$maxDate.Date",
"Value": "$maxDate.Value"}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314291.html
標籤:MongoDB mongodb-查询 皮蒙戈
