如何使用mongoose在MongoDB中的日期字段上创建查询?

时间:2023-01-18 08:02:45

I am trying to query a collection in Mongo database, to get all record with Time field in a date range. Time is defined as Date in database.
My environment: Node.js, Express, Jade, javascript.

我正在尝试在Mongo数据库中查询一个集合,以便在一个日期范围内获取所有带有Time字段的记录。时间定义为数据库中的日期。我的环境:节点。js,表达、玉石、javascript。

This is the javascript code:

这是javascript代码:

var query = {};
var timeQuery = {};
timeQuery["$lt"] = new Date().toISOString();
query["Time"] = timeQuery;
console.log(query);
db.model('testruns').find(query).exec(function (err, testruns) {
    console.log(testruns.length);
    // doing something
});

the result printed to console:

打印到控制台的结果:

{ Time: { '$lt': '2014-10-30T15:04:39.256Z' } }
0

{时间:{‘$lt’:‘2014-10-30t15:04:41 . 256z '} 0

The query returns 0 results (there should be more)

查询返回0个结果(应该有更多)

By the way... Running date queries from RoboMongo returns results, just the wrong ones. for example:

顺便说一下…RoboMongo的运行日期查询会返回错误的结果。例如:

db.testruns.find({Time : {"$gte" : new Date("2014-10-30T15:13:37.199Z")}})

returns all records.

返回所有记录。

What I tried: This one, that one, another one, mongoose documentation of course, and many more results from google.

我尝试了:这个,那个,另一个,当然是mongoose文档,以及谷歌的更多结果。

Most of them give the same answer, none of them works for me. HELP!

他们中的大多数人给出了相同的答案,但没有一个对我有效。的帮助!

2 个解决方案

#1


0  

as far I see you are not including the field to reference in the query, can you try this: I assume your field name is 'time'

到目前为止,我看到您不包括在查询中引用的字段,您可以试试这个:我假设您的字段名是“time”

var date = new Date(); //or the date you want to compare
db.model('testruns').find({"Time":{"$lt":date}}).exec(function (err, testruns) {
    console.log(testruns.length);
    // doing something
});

#2


0  

The problem was related to a schema definition, not directly to this code. The code of the query was correct. a schema definition had this field(Time) as String, which caused MongoDB to try and find a string in a date field...

问题与模式定义有关,而不是直接与此代码有关。查询的代码是正确的。模式定义将这个字段(时间)作为字符串,这导致MongoDB试图在一个日期字段中找到一个字符串……

#1


0  

as far I see you are not including the field to reference in the query, can you try this: I assume your field name is 'time'

到目前为止,我看到您不包括在查询中引用的字段,您可以试试这个:我假设您的字段名是“time”

var date = new Date(); //or the date you want to compare
db.model('testruns').find({"Time":{"$lt":date}}).exec(function (err, testruns) {
    console.log(testruns.length);
    // doing something
});

#2


0  

The problem was related to a schema definition, not directly to this code. The code of the query was correct. a schema definition had this field(Time) as String, which caused MongoDB to try and find a string in a date field...

问题与模式定义有关,而不是直接与此代码有关。查询的代码是正确的。模式定义将这个字段(时间)作为字符串,这导致MongoDB试图在一个日期字段中找到一个字符串……