For a project I'm working on, using the excellent mgo driver, I needed to be able to query the MongoDB collection by the ObjectId's timestamp.
And while I was inserting dummy data, I had no obvious way to generate a new unique ObjectId with a timestamp (the timestamp itself wasn't unique) so I wrote this little helper function.
Note that this function isn't the same as bson.NewObjectIdWithTime,
bson.NewObjectIdWithTime works for generating a timestamp-only ObjectId that you can query the database with, but not for insertion.
1 2 3 4 5 |
func makeTimeObjectId(t time.Time) bson.ObjectId { oid := bson.NewObjectId().Hex() // Generate a new unique object id and convert it to a hex string nid := fmt.Sprintf("%x%s", t.Unix(), oid[8:]) //strip the time out of the objectid and use our timestamp instead return bson.ObjectIdHex(nid) } |