如何执行此mongo聚合?

时间:2019-03-25 13:55:56

标签: mongodb

我在mongo中有一个收藏集,看起来像这样:

{
    "_id" : ObjectId("5c98d6f383d67f243730443b"),
    "date" : ISODate("2019-03-24T00:00:00Z"),
    "symbol" : "F:ABCD",
    "symbolCode" : "wcgahi8gap",
    "close" : 8.09,
    "high" : 24.82,
    "low" : 8.09,
    "numPoints" : 8,
    "open" : 20.84,
    "volume" : 21183
}
{
    "_id" : ObjectId("5c98d6f383d67f243730443c"),
    "date" : ISODate("2019-03-25T00:00:00Z"),
    "symbol" : "F:ABCD",
    "symbolCode" : "wcgahi8gap",
    "close" : 1.77,
    "high" : 23.47,
    "low" : 1.77,
    "numPoints" : 3,
    "open" : 8.21,
    "volume" : 9645
}

显示当天结束时的股票价格。我正在尝试编写汇总,以计算1天间隔内每只股票的变化/百分比变化。因此,它应该只是当日休市字段和前一天休市字段之间的差。我怎样才能做到这一点?

这是我到目前为止所拥有的:

  const results = await Price.aggregate([
    { $match: { date: { $gte: yesterday } } },
    { $sort: { date: 1 } },
    { $group: { '_id': '$_id',
      'old': {
        $sum: { $cond: [{ '$eq': [ '$date', yesterday ] }, '$close', 0] }
      },
      'new': {
        $sum: { $cond: [{ '$eq': [ '$date', today ] }, '$close', 0] }
      } } },
    { $project: { date: 1, symbol: 1, difference: { $subtract: ['$new', '$old'] } } }
  ])

我知道我错过了小组赛的重要组成部分,但我无法弄清楚。

1 个答案:

答案 0 :(得分:0)

这就是我的做法:

  const results = await Price.aggregate([
    { $match: { date: { $gte: yesterday } } },
    { $sort: { date: 1 } },
    { $group: { '_id': '$symbol',
      old: {
        $sum: {
          $cond: [{ $eq: ['$date', yesterday] }, '$close', 0]
        }
      },
      new: {
        $sum: {
          $cond: [{ $eq: ['$date', today] }, '$close', 0]
        }
      } } },
    { $project: {
      symbol: '$_id',
      change: { $subtract: ['$new', '$old'] },
      changePrc: { $divide: [{ $subtract: ['$new', '$old'] }, '$old'] }
    } }
  ])

this的答案用于帮助。