Mongo聚合和基本查询

时间:2018-10-13 11:43:32

标签: mongodb

我在mongo db中有一个具有以下给定格式的多个文档的库存集合。

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

我想写几个查询:

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

我对前两个问题有书面查询

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 个答案:

答案 0 :(得分:1)

对于过去n年的股票,您可以尝试以下查询

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

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

相关问题