我正在使用AlphaVantage API获取金融市场数据并将其存储在mongo中。我的mongo方案是这样的:
import * as mongoose from 'mongoose'
export interface Symbol extends mongoose.Document {
code: string,
data_frame: object[],
createdAt: Date,
updatedAt: Date
}
const symbolSchema = new mongoose.Schema({
code:{
type: String,
required: true,
unique: true
},
data_frame:{
type: [Object],
default: {}
},
createdAt:{
type: Date,
default: Date.now()
},
updatedAt:{
type: Date
}
}, {timestamps: true})
export const Symbol = mongoose.model<Symbol>('Symbol', symbolSchema)
这就是Alpha Vantage API的数据呈现方式:
[
{
"2021-07-02": {
"1. open": "17.39",
"2. high": "17.63",
"3. low": "17.25",
"4. close": "17.43",
"5. adjusted close": "17.43",
"6. volume": "24228000",
"7. dividend amount": "0.0000",
"8. split coefficient": "1.0"
},
"2021-07-01": {
"1. open": "16.86",
"2. high": "17.32",
"3. low": "16.82",
"4. close": "17.2",
"5. adjusted close": "17.2",
"6. volume": "39101898",
"7. dividend amount": "0.0000",
"8. split coefficient": "1.0"
},
"2021-06-30": {
"1. open": "17.15",
"2. high": "17.46",
"3. low": "17.02",
"4. close": "17.07",
"5. adjusted close": "17.07",
"6. volume": "28807699",
"7. dividend amount": "0.0000",
"8. split coefficient": "1.0"
...
]
我将历史数据存储为对象,就像它来自AlphaVantage API一样。我在跳过和限制来自我自己的API的查询时遇到了问题。换句话说,我只想接收x
历史数据,并且能够应用分页,但我不能。
之前,我使用Python,并将Alpha Vantage历史数据保存为数字数组。我使用了以下代码片段,并能够应用文档限制。有人能帮我吗?
model.findOne({"code": req.query.code}, {data_frame: {$slice:-req.query.limit}})
.then(obj=>res.json(200, obj.data_frame))
.catch(next)
我尝试了以下命令,但没有成功:
model.aggregate([
{ $match: { "code": req.query.code } },
{ $unwind: "$data_frame" },
{ $limit: 2 }
])
.then(obj=>res.json(200, obj))
.catch(next)
而这个。。
model.find({"code": req.query.code})
.slice('data_frame', 2)
.then(obj=>res.json(200, obj))
.catch(next)
基本上,每次返回时都必须更新页面。
let page = 0
let itemsPerPage = 2
model.aggregate([
{ $match: { "code": req.query.code } },
{ $unwind: "$data_frame" },
{ $limit: itemsPerPage },
{ $skip:itemsPerPage*page}
])
.then(obj=>res.json(200, obj))
.catch(next)
好吧,我按如下方式解决了这个问题:
我的错误是存储Alpha Vantage API捕获的数据。因此,根据这些捕获的数据,在保存到mongo之前,我应用了以下命令,如下所述:
let documents = []
Object.entries(data["Time Series (Daily)"]).forEach(function (data) {
const index_date = {date: Date.parse(data[0])}
Object.entries(index_date).forEach(([key, value]) => { data[1][key] = value })
documents.push(data[1])
})
因此,保存的数据看起来是这样的:
"data_frame": {
"1. open": "113.41",
"2. high": "114.36",
"3. low": "110.76",
"4. close": "111.28",
"5. adjusted close": "111.28",
"6. volume": "22014500",
"7. dividend amount": "0.0000",
"8. split coefficient": "1.0",
"date": 1625097600000
}
然后通过@Hanuman-Singh响应本身,您可以限制查询并应用分页。