我一直在对我正在开发的项目进行类似的查询,很高兴看到我得出了类似的结论。
我的传入数据来自 Robinhood 的 API;它看起来和你的很相似,但是给了我字符串中的日期戳,所以我添加了一个 $toDate 和 $toString 来将字符串翻转到 Date 对象。我可能会选择将传入的日期戳转换为 Ruby 中的 Time 对象,然后在此处删除额外的工作。
我仍在完善我的分组,因为我不确定我是否真的需要两个。我的传入流有时会重复数据(每秒,由于字符串日期戳的情况),所以第一组是清理它,以免错误地膨胀第二组中的 { "$sum": "$volume" }。
我的 $project 在请求的前一分钟的 59 秒范围内返回我的 100 万根烛台数据。这些键与 Robinhood 的 API 历史记录相匹配,因此我可以将它们视为代码中的同一个对象。
var date_now = new Date(new ISODate("2019-10-21T20:00:00.000Z"))
var date_end = new Date(date_now.getTime() - 1000 * 1)
var date_begin = new Date(date_now.getTime() - 1000 * 60 * 10)
db.quotes.aggregate([
{ "$addFields": { "date": { "$toDate": "$time_pulled" } } },
{ $match: { symbol: "NUGT",
date: { "$gte": date_begin,
"$lt": date_end } } },
{ $group: { _id: "$date", // group by date to eliminate dups
"symbol": { "$first": "$symbol" },
"price": { "$max": "$last_trade_price" },
"volume": { "$max": "$volume" } } },
{ $sort: { _id: 1 } }, // sort by date to get correct first/last prices
{ $group: { _id: "$symbol",
//"date_begin": { "$first": { "$toString": "$_id" } },
//"date_end": { "$last": { "$toString": "$_id" } },
"high_price": { "$max": "$price" },
"low_price": { "$min": "$price" },
"open_price": { "$first": "$price" },
"close_price": { "$last": "$price" },
"volume": { "$sum": "$volume" } } },
{ $project: { _id: 1,
begins_at: { "$toString": date_begin },
volume: 1,
high_price: 1,
low_price: 1,
open_price: 1,
close_price: 1 } }
])
结果:
/* 1 */
{
"_id" : "NUGT",
"high_price" : "26.860000",
"low_price" : "26.740000",
"open_price" : "26.834200",
"close_price" : "26.820000",
"volume" : 392086.0,
"begins_at" : "2019-10-21T19:50:00.000Z"
}