简体   繁体   中英

Comparison query operator ObjectId <-> Date

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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