MongoDB 日期比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18096307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB date comparison
提问by Giovanni Lovato
How MongoDB performs date comparison? I tried a few test on the MongoDB shell:
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)" ] }
]
Now I'll try to get all objects with a date in dates
greater than Aug 30, 2000.
现在,我将尝试获取日期dates
大于 2000 年 8 月 30日的所有对象。
> db.test.find( { "dates" : { $gt : new Date("Aug 30, 2000") } } )
[
]
As expected, the document doesn't match. Using "Aug 30, 1999", instead...
正如预期的那样,文档不匹配。使用“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)" ] }
]
The document matches! What am I missing?
文件匹配!我错过了什么?
回答by user1498724
It seems to be related to the date conversion.
它似乎与日期转换有关。
What version of MongoDB are you using? In the online shell of MongoDB I get the following:
您使用的是哪个版本的 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)"
However, if I try in MongoDB 2.2.2
但是,如果我在 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")
In your case, It seems that MongoDB is indexing the string version and then performing a basic string comparison which would explain the results your are getting.
在您的情况下,MongoDB 似乎正在索引字符串版本,然后执行基本的字符串比较,这将解释您获得的结果。