mongodb - MongoDB 存储和查询价格历史
问题描述
我正在使用一组数据,即产品目录。只有大约 20k 件商品,价格变化很少发生。每月最多可能有 100 次更新。
但是,在这种情况下,价格变化是有趣的事情,我想长期跟踪价格。
我正在尝试找到以易于查询的方式存储价格数据的最佳方式。
目前它存储在产品文档的数组中。只是价格和时间戳。鉴于少量且相当静态的数据集,您将如何设计模型?
另外,还有一个额外的问题,一个过滤器会是什么样子,可以给出当前价格低于前一个价格的产品列表?
示例数据,模型的简化版本:
// Match, current price is lower than previous price
db.TestC.insert({Name: "P1", CurrentPrice: 10.0, PriceHistory: [{Price: 14.0, Timestamp: ISODate("2019-04-26T07:11:11.939Z")}, {Price: 12.0, Timestamp: ISODate("2019-04-27T07:11:11.939Z")}]})
// No match, price history doesn't exist yet
db.TestC.insert({Name: "P2", CurrentPrice: 10.0, PriceHistory: null})
// No match, previous price was lower than current price
db.TestC.insert({Name: "P3", CurrentPrice: 18.0, PriceHistory: [{Price: 14.0, Timestamp: ISODate("2019-04-26T07:11:11.939Z")}, {Price: 12.0, Timestamp: ISODate("2019-04-27T07:11:11.939Z")}]})
在对此进行更多工作后进行编辑:
所以,我终于想出了我需要的东西,并认为我应该分享它以防它帮助某人:
db.TestCollection.aggregate({
'$project': {
'Number': 1,
'AssortmentKey': 1,
'AssortmentName': 1,
'NameExtension': 1,
'Name': 1,
'CurrentPrice': {
'$arrayElemAt': [
'$PriceHistory', -1
]
},
'PreviousPrice': {
'$arrayElemAt': [
'$PriceHistory', -2
]
}
}
}, {
'$match': {
'$expr': {
'$lt': [
'$CurrentPrice.Price', '$PreviousPrice.Price'
]
}
}
})
解决方案
实际上,我会以相同的方式组织文档。请记住,MongoDB 对每个文档有 16 MB 的硬限制,这是非常非常高的限制,在这种情况下几乎无法访问,但它仍然存在。
如果您只需要知道当前价格而没有历史记录,则可以使用投影查询,以避免通过网络发送庞大的数组:
db.TestC.find({Name: 'P1'}, {Name, CurrentPrice}});
至于奖金问题,您可以利用聚合框架:
db.TestC.aggregate([
{
$project: {
Name: 1,
CurrentPrice: 1,
PreviousPrice: { // remove this key if you don't need to have previous price in the result
$arrayElemAt: [
"$PriceHistory",
0 // depends on whether you store prices by pushing to the end of history array, or to the beginning of it
]
},
IsCurrentPriceLower: {
$lt: [
"$CurrentPrice",
{
$arrayElemAt: [
"$PriceHistory",
0 // depends on whether you store prices by pushing to the end of history array, or to the beginning of it
]
}
]
}
},
},
{
$match: {
IsCurrentPriceLower: true
}
}
])
推荐阅读
- ios - iOS Widget 在主屏幕第一次不读取 UserDeafults 值
- java - Android Studio ExoPlayer 我错在哪里
- python-3.x - 基于自定义分隔符将txt文件拆分为多个
- python - 使用 Pandas 根据条件将列位置向右移动
- reactjs - 反应计时器,反应本机计时器,
- r - 计算两个组合列的唯一值
- gitlab - AWS 上的 Gitlab CI 自动缩放 - Gitlab 看不到生成的运行器,也看不到分配的作业
- arrays - Minizinc:在另一个数组中构造出现的数组
- amazon-web-services - 用于实时监控 AWS lambda 和其他实例定价的 API?
- facebook-graph-api - 如何获取 Facebook 帖子的印象数?