mongodb - mongodb:选择嵌入式数组中的最新条目
问题描述
给定具有价格历史记录的项目的以下数据:
{
item: "Item A",
priceHistory: [
{
date: ISODate("2021-04-01T08:32:45.561Z"),
value: 100
},
{
date: ISODate("2021-04-02T08:32:45.561Z"),
value: 200
},
{
date: ISODate("2021-04-04T08:32:45.561Z"),
value: 400
},
{
date: ISODate("2021-04-03T08:32:45.561Z"),
value: 300
},
]
},{
item: "Item B",
priceHistory: [
{
date: ISODate("2021-04-01T08:32:45.561Z"),
value: 1
}
]
}, ...
请注意,该priceHistory
字段未排序。
我想找到每件商品的最新价格:
{
item: "Item A",
price: 400
},{
item: "Item B",
price: 1
}, ...
现在我正在努力选择最新的条目priceHistory
我已经尝试过的
- 我知道我可以
{ $unwind: "$priceHistory" }
使用priceHistory
. - 有了
$max: "$priceHistory.date"
我可以找到最新的date
- 我知道从 MongoDB 4.4 开始,
$last
要获取数组中的最后一项-> 在这里没有用,因为项目不按顺序排列
但我很难将它们整合在一起。
顺便说一句,也许问题出在数据模型本身上?将价格历史记录到自己的收藏中,并且只将最新价格存储在商品本身上是否有意义?
解决方案
演示 - https://mongoplayground.net/p/-LQPcTn_-Aj
db.collection.aggregate([
{ $unwind: "$priceHistory" }, // unwind to individual documents
{ $sort: { "priceHistory.date": -1 } }, // sort by priceHistory.date to get max date at the top (descending)
{
$group: {
_id: "$_id", // group by id back and get priceHistory sorted in descending order by date
price: { $first: "$priceHistory.value" }, // get the first price which is for max date record
item: { $first: "$item"}
}
}
])
推荐阅读
- python-3.x - python3 urllib vimeo HTTP 错误 403:禁止
- xcode - 在 xcode 中使用自定义钥匙串
- javascript - jQuery多选更改事件无法按选择顺序获取选项值
- ada - 如何安装 GtkAda?
- react-native - 图像裁剪选择器通过点击相机将图像保存到图库中反应原生
- c++ - 将数组展开为具有任意数量和类型参数的函数的特定情况
- python - python中是否有任何函数,或者我们可以创建它,我们可以在其中提供输入(字符串)并返回输出(字典)?
- html - 正文背景颜色仅应用于元素
- java - 在 Controller 中使用 @Autowired 和 @Qualifier 更改服务的数据源
- c# - 将项目从 2005 年的可视化 Web 开发人员转移到 2015 年的可视化 Web 开发人员