我在 MongoDB 上有以下集合(_id為了清楚起見,我省略了該欄位):
[
{
"stock": "Stock1",
"value": 12,
"month": 1,
"year": 2019
},
{
"stock": "Stock1",
"value": 13,
"month": 2,
"year": 2019
},
{
"stock": "Stock1",
"value": 14,
"month": 1,
"year": 2020
},
{
"stock": "Stock1",
"value": 15,
"month": 2,
"year": 2020
},
{
"stock": "Stock2",
"value": 6,
"month": 1,
"year": 2019
},
{
"stock": "Stock2",
"value": 5,
"month": 2,
"year": 2019
}
]
我希望檢索每個檔案stock的最新(最大)year可用檔案,這樣我最終會得到以下內容:
[
{
"stock": "Stock1",
"value": 14,
"month": 1,
"year": 2020
},
{
"stock": "Stock1",
"value": 15,
"month": 2,
"year": 2020
},
{
"stock": "Stock2",
"value": 6,
"month": 1,
"year": 2019
},
{
"stock": "Stock2",
"value": 5,
"month": 2,
"year": 2019
}
]
我在每個誘惑編程回圈stock,并在第一步查詢的最后year使用find({"stock": "Stockx"}).sort({"year": -1}).limit(1)和在第二步查詢find({"stock": "Stockx", "year": maxyearforStockx"})。有沒有更優雅的方式來使用findoraggregate命令來做到這一點?
任何幫助將不勝感激!
uj5u.com熱心網友回復:
$sort- 按year降序排序。$group- 按stock和分組year。$group- 分組stock并取stockYearItems(來自 2)的第一項。$unwind- 將items.stockYearItems陣列解構為多個檔案。$replaceRoot- 用新檔案替換輸入檔案以顯示stock檔案。
db.collection.aggregate({
"$sort": {
"year": -1
}
},
{
$group: {
_id: {
"stock": "$stock",
"year": "$year"
},
stockYearItems: {
$push: "$$ROOT"
}
}
},
{
$group: {
_id: "$_id.stock",
items: {
$first: "$$ROOT"
}
}
},
{
$unwind: "$items.stockYearItems"
},
{
"$replaceRoot": {
"newRoot": "$items.stockYearItems"
}
})
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/371139.html
標籤:MongoDB mongodb-查询 nosql 聚合框架 文档
