在原始查询,timestamp
是一个简单的字符串字段和Date()
将被视为在蒙戈外壳的字符串。相比那些操作数会像其他任何字符串比较:
$ mongo
MongoDB shell version: 2.2.0-rc1-pre-
connecting to: test
> db.foo.drop()
true
> db.foo.insert({ x: Date() });
> db.foo.find()
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
> sleep(1000)
null
> db.foo.find({ x: { $lt: Date() }});
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
> db.foo.find({ x: { $gt: Date() }});
>
ISODate()
是JS相当于为Mongo date fields,并且它使用$gt
或$lt
运营时不与字符串值相媲美:
> db.foo.find({ x: { $gt: ISODate() }});
> db.foo.find({ x: { $lt: ISODate() }});
> db.foo.find({ x: { $ne: ISODate() }});
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
> db.foo.insert({x: ISODate() });
> db.foo.find({ x: {$gt: Date() }});
> db.foo.find({ x: {$lt: Date() }});
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
> db.foo.find({ x: {$ne: Date() }});
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
{ "_id" : ObjectId("50218fa18930273947a21cf4"), "x" : ISODate("2012-08-07T21:58:57.350Z") }
>
蒙戈的确定义了compare orders between types,其中字符串出现在日期之前,但是与同一字段在整个集合中可能具有不同类型时的排序顺序有关。
请注意,如果您经常想要删除旧记录(例如,在批处理过程中),您可能对TTL collections感兴趣,这是即将发布的2.2版本中的新功能。 Kristina Chodorow还在this blog entry上写了一篇有趣的介绍。
@ Error-SyntacticalRemorse:虽然有更多的上下文很好,但[NAA指南](https://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when如果它具有被推荐的基本代码元素的实际名称,则它明确地不标注任何“NAA”。今后不要标记这种类型的答案。 – 2017-08-25 00:07:47
@ Error-SyntacticalRemorse:VLQ,那么?当我编辑时,我注意到了自动downvote。但VLQ更不合理。 (假设某人在使用自动装罐自动装箱时会出现标记,这是非常合理的行为。) – 2017-08-25 00:18:07
@ Error-SyntacticalRemorse:不,它是[Community♦](https://stackoverflow.com/users/-1/community),当VLQ/NAA标记通过编辑发生争议时,会自动发出downvote。 – 2017-08-25 00:20:14