简体   繁体   English

mongodb查询以获取两个日期范围内的文档

[英]mongodb query to get documents within two date range

my documents have a field with date type as below. 我的文档有一个日期类型如下的字段。

{ 
    "_id" : ObjectId("568bae0fcfe23a50879d45fc"),
    "data": {
          "createdDate" : ISODate("2015-12-17T22:25:24.973+0000")
    }
}

how can i get all documents where data.createdDate <= todayDate and data.createdDate >= todayDate-20days. 我如何获取data.createdDate <= todayDate和data.createdDate > = todayDate-20days的所有文档。

i tried with below query, which is working fine. 我尝试使用下面的查询,它工作正常。

db.myTable.aggregate([
    {$match: {"data.createdDate": {$lte: new Date(), $gte: new Date(new Date().setDate(new Date().getDate()-20))}}}
])

but this query considers time also. 但是此查询也会考虑时间。 I want to compare only with respect to date. 我只想就日期进行比较。

if you want to compare with respect to date , you should set createdDate with hours, minutes, seconds and milliseconds to zero before storing into database. 如果要相对于date进行比较,则在存储到数据库之前,应将createdDate的小时,分​​钟,秒和毫秒设置为零。

If you have such date in db, try below query 如果您在数据库中有这样的日期,请尝试以下查询

 db.collection.aggregate([
    {$match: {"data.createdDate": {$lte: new Date().setHours(0,0,0,0), $gte: new Date(new Date().setDate(new Date().getDate()-20)).setHours(0,0,0,0)}}}
])

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

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