Reputation: 1855
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?
Upvotes: 0
Views: 163
Reputation: 151220
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.
Upvotes: 1