Re: [mongodb-user] Can I filter ObjectId type by time?

234 views
Skip to first unread message

Sam Millman

unread,
Jan 15, 2013, 2:32:25 PM1/15/13
to mongod...@googlegroups.com
You can actually query by the date part of the _id if you sneak it a little, check this snide answer: http://stackoverflow.com/questions/8749971/can-i-query-mongodb-objectid-by-date

I guess the side effects is of sending in something that is bigger than a normal date type and, of course, the index complications associated with that, but it should be relatively minor if you can't avoid it.


On 15 January 2013 19:20, Greg Silin <gr...@klout.com> wrote:
We have some legacy code where a timestamp is represented as an ObjectId string. I realize that's silly, but assume I can't change the fact for time being.

I can extract the timestamp from field.  However, can I safely filter documents with a date range on this field?

Basically, given startAt & endAt timestamps, could I construct ObjectId(startAt) & ObjectId(endAt) and then do something like:

db.myCollection.find({createdAt: {$gte: ObjectId(startAt), $lte: ObjectId(endAt)})

Does this have possible side effects I'm not thinking about (considering ObjectId's also containing the machine id, among other things).

Thanks!
-greg

--
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
See also the IRC channel -- freenode.net#mongodb

Jeff Lee

unread,
Jan 15, 2013, 2:33:14 PM1/15/13
to mongod...@googlegroups.com
Greg,

Do you mean you have a key ( createdAt ) where all the values are timestamp types except for a few bad ones that are ObjectIds?  Can you locate them using $type = 7 or if they're strings type = 2?

e.g.

s01:PRIMARY> db.thetimes.save({id:1, created:new Timestamp()})
s01:PRIMARY> db.thetimes.save({id:2, created:ObjectId()})
s01:PRIMARY> db.thetimes.find()
{ "_id" : ObjectId("50f5ae2599902ea9daf51d4e"), "id" : 1, "created" : Timestamp(0, 0) }
{ "_id" : ObjectId("50f5ae2999902ea9daf51d50"), "id" : 2, "created" : ObjectId("50f5ae2999902ea9daf51d4f") }
s01:PRIMARY> db.thetimes.find({ created:{$type:7}})
{ "_id" : ObjectId("50f5ae2999902ea9daf51d50"), "id" : 2, "created" : ObjectId("50f5ae2999902ea9daf51d4f") }

Jeff Lee

unread,
Jan 15, 2013, 2:39:31 PM1/15/13
to mongod...@googlegroups.com
Ah, sorry.  Just re-read your post.  I've been doing some cleanup by type so I read that as you wanted to find and change the docs with the objectid type.

Greg Silin

unread,
Jan 16, 2013, 4:34:03 PM1/16/13
to mongod...@googlegroups.com
Thank you!  Exactly what I was asking about.
Reply all
Reply to author
Forward
0 new messages