简体   繁体   English

使用FindOne按日期范围查询MongoDb(通过Nodejs本机驱动程序)

[英]Query MongoDb by date range using FindOne (via Nodejs native driver)

I am trying to query MongoDb using a date range in my FindOne statement, but I cannot get it to work. 我正在尝试在我的FindOne语句中使用日期范围查询MongoDb,但无法使其正常工作。 I am using the Nodejs native driver. 我正在使用Nodejs本机驱动程序。 I've tried various options, but nothing is returning the expected record. 我尝试了各种选择,但没有任何结果返回预期的记录。

Here is my pseudo-code - 这是我的伪代码-

console.log(sDate);                    // displays  Fri Jun 20 2014 10:00:00 GMT+1000 (AUS Eastern Standard Time)
var sDateISO = sDate.toISOString();
console.log(sDateISO);                 // displays  2014-06-20T00:00:00.000Z 

// all of these return null object
db.collection('events').findOne(
  { eventStartDate: { $lte: new Date(sDate)}},
  function(err, obj) { console.dir(obj); }        // displays  null
);

db.collection('events').findOne(
  { eventStartDate: { $lte: (sDate) }},
  function(err, obj) { console.dir(obj); }        // displays  null
);

db.collection('events').findOne(
  { eventStartDate: { $lte: new Date(sDateISO) }},
  function(err, obj) { console.dir(obj); }        // displays  null
);

db.collection('events').findOne(
  { eventStartDate: { $lte: (sDateISO) }},
  function(err, obj) { console.dir(obj); }        // displays  null
);

However, if I run this in RoboMongo, the record is returned as expected - 但是,如果我在RoboMongo中运行此命令,则记录将按预期返回-

在此处输入图片说明

========== ==========

UPDATE UPDATE

My problem was elsewhere in my code -- I had a type mismatch problem in a separate parameter passed to the FindOne query. 我的问题在代码的其他地方-我在传递给FindOne查询的单独参数中遇到类型不匹配的问题。

As stated in the documentation , and confirmed by Christian P below, I can use my Javascript date object sDate in the FindOne query directly. 文档中所述,并在下面得到Christian P的确认,我可以在FindOne查询中直接使用Javascript日期对象sDate

I used a typeOf function (found here ) to confirm sDate is indeed a Date object. 我使用typeOf函数(在此处找到)来确认sDate确实是Date对象。

So, after inspecting all other variables in my actual code, I found the problem elsewhere, unrelated to the Date object / parameter. 因此,在检查了我的实际代码中的所有其他变量之后,我在其他地方发现了与Date对象/参数无关的问题。

ISODate is a wrapper around Date object in the MongoDB shell. ISODate是MongoDB Shell中Date对象的包装。 Robomongo embeds the same JavaScript engine as mongo shell, that's why your query works in RoboMongo. Robomongo嵌入了与mongo shell相同的JavaScript引擎,这就是您的查询在RoboMongo中工作的原因。

To query the date range you can simply use the Date object in your query: 要查询日期范围,您只需在查询中使用Date对象即可:

db.collection('events').findOne(
  { eventStartDate: { $lte: sDate}},
  function(err, obj) { 
      console.dir(obj); 
  }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM