在MongoDB中搜索日期条目,每分钟都有很多条目

时间:2016-02-26 22:48:18

标签: javascript node.js mongodb find

编辑以获得更好的解释:

我整天都有很多参赛作品

我的收藏中的文件是这样的:

{
"type": "Watches",
"timestamp": ISODate("2016-02-23T21:00:00.000Z"),
"price": 100.77
}
{
"type": "Watches",
"timestamp": ISODate("2016-02-23T20:50:00.000Z"),
"price": 200.77
}
{
"type": "Watches",
"timestamp": ISODate("2016-02-24T21:00:00.000Z"),
"price": 300.77
}
{
"type": "Watches",
"timestamp": ISODate("2016-02-24T20:51:00.000Z"),
"price": 94.77
}

条目以分钟为单位保存。但是,有些日子根本没有参赛作品。

那么,如何在21:00搜索所有条目,直到获得10个结果? (跳过没有条目的日子)

我的第一次尝试就像制作一个数组:

  var array_of_dates =[ Thu Feb 24 2016 21:00:00 GMT-0300 (ART),
                        Wed Feb 23 2016 21:00:00 GMT-0300 (ART) ]

并使用{' $ in' :array_of_dates}但是,如果有些日子没有进入,我得到的结果不到10个。

1 个答案:

答案 0 :(得分:0)

关于

  

那么,我怎样才能在21:00搜索所有条目,直到得到10个结果?

这个答案很有帮助:https://stackoverflow.com/a/2943685/3359432

在MongoDB中,您可以在日期字段中使用$ lt,$ gt等。确保创建要比较的Date对象并将其传递给查询查询。看看代码......

Mongo Shell中的示例查询:

db.collection('myCollection').find({
    timestamp: {$gt: new Date(+new Date() - 10* 60 * 1000)} //time in milliseconds
}).limit(10).toArray()

上述查询将找到10个文档,这些文档距离当前时间10分钟(10 * 60 * 1000毫秒)。这是在Mongo Shell中执行的命令。

如果你在Node.js中使用Mongoose,我可以使用以下查询:

yourCollectionSchema.find({
      timestamp: {
        '$gt': new Date(+new Date() - 10 * 60  * 1000) //time in milliseconds
      }
    })
.then(function(docs){
    console.log(docs)// Use the data
});