【问题标题】:MongoDB date comparisonMongoDB日期比较
【发布时间】:2013-08-07 15:08:40
【问题描述】:

MongoDB 如何进行日期比较?我在 MongoDB shell 上尝试了一些测试:

> db.test.insert( { "dates" : [ new Date("Jul 21, 1983"), new Date("Aug 7, 1999") ] } )
"ok"
> db.test.find()

[ 
  {   "_id" : {   "$oid" : "5201e8b7cc93742c160bb9d8"   },   "dates" : [   "Thu Jul 21 1983 00:00:00 GMT+0200 (CEST)",   "Sat Aug 07 1999 00:00:00 GMT+0200 (CEST)" ]   }
]

现在我将尝试获取日期在dates 中大于 2000 年 8 月 30 日的所有对象。

> db.test.find( { "dates" : { $gt : new Date("Aug 30, 2000") } } )

[

]

正如预期的那样,文档不匹配。改用“1999 年 8 月 30 日”...

> db.test.find( { dates : { $gt : new Date("Aug 30, 1999") } } )

[ 
  {   "_id" : {   "$oid" : "5201e8b7cc93742c160bb9d8"   },   "dates" : [   "Thu Jul 21 1983 00:00:00 GMT+0200 (CEST)",   "Sat Aug 07 1999 00:00:00 GMT+0200 (CEST)" ]   }
]

文档匹配!我错过了什么?

【问题讨论】:

    标签: mongodb datetime


    【解决方案1】:

    好像和日期转换有关。

    您使用的是哪个版本的 MongoDB? 在 MongoDB 的在线 shell 中,我得到以下信息:

    > new Date("Jul 21, 1983")
    "Thu Jul 21 1983 00:00:00 GMT+0200 (CEST)"
    > new Date("Aug 7, 1999")
    "Sat Aug 07 1999 00:00:00 GMT+0200 (CEST)"
    
    > new Date("Aug 30, 2000")
    "Wed Aug 30 2000 00:00:00 GMT+0200 (CEST)"
    > new Date("Aug 30, 1999")
    "Mon Aug 30 1999 00:00:00 GMT+0200 (CEST)"
    

    但是,如果我在 MongoDB 2.2.2 中尝试

    > new Date("Jul 21, 1983")
    ISODate("1983-07-20T22:00:00Z")
    > new Date("Aug 7, 1999")
    ISODate("1999-08-06T22:00:00Z")
    > new Date("Aug 30, 2000")
    ISODate("2000-08-29T22:00:00Z")
    > new Date("Aug 30, 1999")
    ISODate("1999-08-29T22:00:00Z")
    

    在您的情况下,似乎 MongoDB 正在索引字符串版本,然后执行基本的字符串比较,这将解释您得到的结果。

    【讨论】:

    • 哦,快!我正在在线 shell 中对其进行测试...谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    相关资源
    最近更新 更多