Comparison query operator ObjectId <-> Date

橙三吉。 提交于 2020-01-06 12:53:08

问题


Is it possible to execute comparison queries $gt, $lt, etc. of a Date against an ObjectId and vice versa? Does the mongodb driver cast this automatically? Does this mongodb server cast this automatically?


回答1:


Yes and no.

It is possible under the JavaScript based methods to get a date from the ObjectId value in which you can use for comparisons. It also should be possible to construct an ObjectId given a specific date value as well, but not seeing the utility of that though. But all are valid and essentialy by date:

ObjectId("53473d87cb495e216c982929") > ObjectId("53473e57cb495e216c98292a")

ObjectId("53473d87cb495e216c982929").getTimestamp() >
ObjectId("53473e57cb495e216c98292a").getTimestamp()

ObjectId("53473d87cb495e216c982929").getTimestamp() >
ISODate("2014-04-11T00:55:35Z")    

So forms such as this will work, even if really not that great a statement:

db.collection.find({ 
    "$where": function() {
         return this._id.getTimestamp() > new Date("2014-01-01");
    }
}

As for the "creation" of _id's they are either done in the "driver" or explicitly by the user, or if still omitted the server will generate one.



来源:https://stackoverflow.com/questions/23003588/comparison-query-operator-objectid-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!