简体   繁体   English

如何在MongoDB中按日期查询文档?

[英]How to query documents by Date in MongoDB?

My events colleciton stores the following documents: 我的活动学院存储以下文档:

{
  "_id": {
      "$oid": "537b2a232a47f21830ae5b7b"
  },
  "startTime": {
      "$date": "2014-05-18T21:00:00.000Z"
  },
  "endTime": {
      "$date": "2014-05-18T23:00:00.000Z"
  }
},
{
  "_id": {
    "$oid": "537af8136c4162d0379e2139"
  },
  "startTime": {
    "$date": "2014-05-19T20:30:00.000Z"
  },
  "endTime": {
    "$date": "2014-05-19T21:30:00.000Z"
  }
}

How could I query events by specific startTime in like the following: 如何通过特定的startTime查询事件,如下所示:

var startTime = '2014-05-18T20:00:00.000Z';

db.collection.find({startTime: {$eq: startTime}});

My problem is I need ignore time and use only date in the query. 我的问题是我需要忽略时间,只在查询中使用日期。 How could I construct my query? 如何构建查询?

Define a date at midnight of the day you want to query and at midnight of the following day. 在您要查询的当天的午夜和第二天的午夜定义日期。 Then use the $lt (less-than) and $gt (greater-than) operators to get all results in the timespan between these two points in time. 然后使用$ lt (小于)和$ gt (大于)运算符来获取这两个时间点之间的时间范围内的所有结果。

var from = new Date('2014-05-18T20:00:00.000Z');
var to = new Date('2014-05-19T20:00:00.000Z');

db.collection.find({startTime: {$gt: from, $lt:to}});

You need to create Date objects this should help 您需要创建Date对象,这应该有所帮助

var start = new Date(2010, 3, 1);
var end = new Date(2010, 4, 1);

http://cookbook.mongodb.org/patterns/date_range/ http://cookbook.mongodb.org/patterns/date_range/

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

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