Using the Java driver, what’s the best way to convert an ObjectID to/from a string with Base64 encoding?
The ObjectIds will be part of a URL so I’d like to shorten them a bit.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The ObjectId class does have a toString() method, and a string may be provided in the constructor. However, these strings are base-16 (hexadecimal), and may bot be what you are looking for.
The API information may be found here:
http://api.mongodb.org/java/current/
For base 64 encoding, a colleague of mine suggested that it may be preferable to use the toByteArray() method, and convert that to a base 64 string. Going the other way, the ObjectId constructor may be passed a byte array.
A Google search for “java library base64 encoding” reveals another Stack Overflow question that contains more detail on converting byte arrays to base 64 strings and back again.
Decode Base64 data in Java
The above thread contains a link to the base64 class, part of the Apache Commons Codec.
http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html
Hopefully this will get you where you need to go, or at least give you some additional options to consider.