【发布时间】:2019-03-21 15:05:22
【问题描述】:
我正在尝试使用以下管道在 mongo 中聚合一个集合:
const results = await Price.aggregate([
{ $match: { date: today } },
{ $unwind: '$points' },
{ $match: { 'points.time': { $gte: start, $lte: now } } },
{ $sort: { 'points.time': 1 } },
{ $project: {
'high': { $max: '$points.price' },
'low': { $min: '$points.price' },
'open': { $arrayElemAt: ['$points', 0] },
'close': { $arrayElemAt: ['$points', -1] }
} }
])
但是$arrayElemAt 运算符可能无法正常工作,因为前面的阶段之一(我相信$unwind)将我在文档中的点数组转换为对象。我该如何解决这个问题?
示例文档:
{
"_id" : ObjectId("5c93ac3ab89045027259a23f"),
"date" : ISODate("2019-03-21T00:00:00Z"),
"symbol" : "CC6P",
"points" : [
{
"_id" : ObjectId("5c93ac3ab89045027259a244"),
"volume" : 553,
"time" : ISODate("2019-03-21T09:35:34.239Z"),
"price" : 71
},
{
"_id" : ObjectId("5c93ac3ab89045027259a243"),
"volume" : 1736,
"time" : ISODate("2019-03-21T09:57:34.239Z"),
"price" : 49
},
....
],
我的预期结果是一个对象数组,其中应该传递给项目阶段的点应该是第二个$match 中指定范围内的点。我尝试合并两个$match 阶段并删除$unwind 阶段,错误消失了,但是没有应用时间范围
【问题讨论】:
-
您在第二阶段有
$unwindedpoints数组。除非您不显示一些示例文档和您期望的结果,否则不能说。 -
@anthonywinzlet 已编辑问题
标签: mongodb mongoose aggregation-framework