【问题标题】:Mongo aggregation and basic queriesMongo 聚合和基本查询
【发布时间】:2018-10-13 20:56:00
【问题描述】:

我在 mongo db 中有一个包含以下格式的多个文档的股票集合。

{
  Id: ‘RELI’
  Date: ‘2018-10-13’
  Price: 900
}

我想写几个查询:

  1. date1 和 date2 之间股票的价格序列。
  2. 股票价格序列
  3. d1 和 d2 之间的 n(股票 ID 数组,例如 [Id1,Id2...] )股票的价格。
  4. 基于粒度(每周和每月)的过去 n 年的股票价格。只需要每周和每月的数据点。 过去 n 个月

我已经写了前 2 个问题的查询

1. db.stocks.find({
  "id":"REL1",
  "price":{
     "$gte": ISODate(d1),
     "$lt": ISODate(d2)
   }
})


2.// Calculate the today’s date
   let d1 = new Date()
   // n is the number of months for which we are trying to fetch the 
   data
   Let d2 = d1.setMonth(d.getMonth() - n);

   db.stocks.find({
      "id":"REL1",
      "price":{
            "$gte": ISODate(d1),
            "$lt": ISODate(d2)
       }
    })

你们能帮我解决第三个和第四个问题吗,或者帮我优化我写的前两个查询

【问题讨论】:

  • 请尽量广泛地解释你的两个观点。
  • 1.我想获取 date1 和 date2 2 之间 n 个股票的价格。最后 n 年(例如 n = 1)年的股票价格。只想要每周和每月的数据点@AnthonyWinzlet

标签: mongodb


【解决方案1】:

对于最近n年的股票,你可以试试下面的查询

db.collection.find({
  "id": "REL1",
  "$expr": {
    "$eq": [
      { "$year": {
        "$dateFromString": { "dateString": "$Date" }
      }},
      2018
    ]
  }
})

对于d1d2 之间的股票,您的第一个查询是否完美?

【讨论】:

  • 是的,第一个查询是正确的,我被困在第三和第四个
  • 第三个你可以使用上面的查询
  • 如何为股票传递多个id?这是我在 mongo 的第一个项目,很抱歉提出愚蠢的问题
  • 您确定您在回答中编写的查询将返回特定股票的每周和每月价格吗?我们不需要传递 id 吗?
  • 更新了答案。
猜你喜欢
  • 1970-01-01
  • 2017-05-02
  • 2015-03-20
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
  • 2021-06-19
  • 1970-01-01
相关资源
最近更新 更多