【发布时间】:2020-09-15 13:56:44
【问题描述】:
在我的 MongoDB 数据库中,我有一个这样的订单集合:
[
{
_id: "mongoId", // 5f5ea6276ba53b06944de28c
createdAt: "2020-09-15T23:07:19.370Z",
totalPrice: 34, // is calculated from the client (quantity * price)
orderDetail: [
{
_id: "product-A-Id", // 5f5ea403e91ed91a44b62c92
quantity: 4,
price: 5.5,
},
{
_id: "product-B-Id",
quantity: 1,
price: 3.5,
},
{
_id: "product-C-Id",
quantity: 1,
price: 8.5,
},
],
},
{
_id: "mongoId",
createdAt: "2020-09-15T23:08:20.370Z",
totalPrice: 15.5,
orderDetail: [
{
_id: "product-C-Id",
quantity: 3,
price: 3,
},
{
_id: "product-D-Id",
quantity: 1,
price: 6.5,
},
],
},
{
_id: "mongoId",
createdAt: "2020-09-15T23:09:25.370Z",
totalPrice: 22.5,
orderDetail: [
{
_id: "product-D-Id",
quantity: 5,
price: 4.5,
},
],
},
]
为了做到这一点,我必须从现在的时间戳(在每个请求中)每两小时生成一次时间序列数据,所需的响应示例如下:
[
{
id: "sales",
data: [
{
x: "00:00",
y: 150,
},
{
x: "22:00",
y: 100,
},
{
x: "20:00",
y: 150,
},
{
x: "18:00",
y: 50,
},
{
x: "16:00",
y: 100,
},
],
},
]
使用 nodejs 和 express like 框架,我可以在过去 2 小时内产生销售额:
const valueDateRange = 2 * 60 * 60 * 1000; // 2 hours
const currentPeriod = new Date(new Date().getTime() - valueDateRange);
// The last 2 hours sales
const calculateTotalSales = await Order.aggregate([
{
$match: { createdAt: { $gte: currentPeriod } },
},
{
$group: { _id: null, TotalAmount: { $sum: "$totalPrice" } },
},
]);
但是现在如何每2小时生成一次时间序列数据,非常感谢您的关注
【问题讨论】:
-
一天有24小时。那是12分。您可以创建一个包含 12 个元素的数组 - 每个点一个。迭代数组并为每个数组元素累积数量值(您必须搜索匹配的小时数)。生成的数组将包含您要查找的数据。有关一些想法,请参阅此帖子:MongoDB: How to query a time-series with incomplete data?
-
我尝试根据温度调整代码,但这有点困难,所以在阅读了 GitGitBoom 的答案后我能够解决它,谢谢@prasad_