Using _id as a timestamp in queries

3,877 views
Skip to first unread message

Andrei Zmievski

unread,
Sep 18, 2010, 11:50:28 AM9/18/10
to mongodb-user
Is it possible to do something like this either in the shell or in the
drivers?

db.foo.find({_id:{$gt:new Date(2010, 06, 03, 0, 0, 0)}})

roger

unread,
Sep 18, 2010, 12:49:26 PM9/18/10
to mongodb-user
Yes, that works:

> db.id.save({_id: new Date()})
> db.id.find()
{ "_id" : "Sat Sep 18 2010 09:43:14 GMT-0700 (PDT)" }
> d = new Date(2010, 8, 18)
> db.id.find({_id: {$gte:d}})
{ "_id" : "Sat Sep 18 2010 09:43:14 GMT-0700 (PDT)" }

in JS months are 0 indexed, so sept is 8, october 9 etc. Consult your
driver doc for particulars there.

-Roger

Kristina Chodorow

unread,
Sep 18, 2010, 9:47:20 PM9/18/10
to mongod...@googlegroups.com
If your talking about using the ObjectId to query for all documents created after a certain date, see http://groups.google.com/group/mongodb-user/browse_thread/thread/86762d3c0ca205bb/, which describes how to do so in PHP (should be generalizable).


--
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com.
To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.


Andrei Zmievski

unread,
Sep 18, 2010, 11:18:54 PM9/18/10
to mongodb-user
This doesn't seem to work for me (on 1.6.0):

> db.foo.find()
{ "_id" : ObjectId("4c08357836572f7b00000000"), "name" : "blah",
"user" : { "$ref" : "users", "$id" : 10 } }
{ "_id" : ObjectId("4c08358b36572f7b00000001"), "name" : "whatever",
"user" : { "$ref" : "users", "$id" : 10 } }
{ "_id" : ObjectId("4c08359536572f7b00000002"), "name" : "new place",
"user" : { "$ref" : "users", "$id" : 11 } }
{ "_id" : ObjectId("4c51d1d7bb256b460426e9c0"), "bar" : 1 }
{ "_id" : ObjectId("4c51d457a21b4a361857826c"), "blah" :
NumberLong( 1 ) }
> ObjectId("4c08357836572f7b00000000").getTimestamp()
"Thu Jun 03 2010 19:06:32 GMT-0400 (EDT)"
> ObjectId("4c51d1d7bb256b460426e9c0").getTimestamp()
"Thu Jul 29 2010 15:09:11 GMT-0400 (EDT)"
> db.foo.find({_id:{$gt:new Date(2010, 06, 10)}})
> db.foo.find({_id:{$gte:new Date(2010, 06, 10)}})

-Andrei

Eliot Horowitz

unread,
Sep 18, 2010, 11:49:53 PM9/18/10
to mongod...@googlegroups.com
You can't use Date to compare timestamp.

You need something like:

prefix = Math.floor((new Date( 2010 , 06 , 10 )).getTime()/1000).toString(16)

db.foo.find( { _id : { $gt : new ObjectId( prefix + "0000000000000000" ) } } )

Reply all
Reply to author
Forward
0 new messages