Mongo-safe encoding and decoding