我在 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": "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
,并在第一步中使用 find({"stock": "Stockx"查询去年的
并在第二步查询中 year
}).sort({"year": -1}).limit(1)find({"stock": "Stockx", "year": maxyearforStockx"} )
。是否有更优雅的方式使用 find
或 aggregate
命令来执行此操作?
任何帮助将不胜感激!
最佳答案
$sort
- 按年份
降序排序。$group
- 按股票
和年份
分组。$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"
}
})
关于mongodb - 如何检索 MongoDB 上每个其他不同字段的字段最大的文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70181954/