MongoDB Change Stream - Decoding UUID from Binary BSON

641 Views Asked by At

I am trying out MongoDB change streams and have come across a problem related to data decoding. In my application (java) i use UUIDs for the documents i store in Mongo. When i turn on the change stream towards the collections i want to listen to, the document ids (:document_key in the change object specification) looks like this:

{"_id"=><BSON::Binary:0x31777440 type=uuid data=0xb426135aabd24af2...>}}

It is not clear to me how I am supposed to decode this back to the original UUID. If i run .to_json on the id i get this:

{“$binary”:{“base64":“rpUsTqcGSZ+YPDzebvq2aA==“,”subType”:“04”}}

Then, decoding the "base64"-field nets me the following nonsense:

,NI<<nh
1

There are 1 best solutions below

0
Zazz On

Solved! Sample code below.

      # Decodes bson_id
  def decode_bson_id(document_key)
    as_json = JSON.parse(document_key.to_json)
    begin
      b64_doc_id = as_json["_id"]["$binary"]["base64"]
      decoded_uuid = b64_doc_id.unpack("m0").first.unpack("H8H4H4H4H12").join('-')
    rescue Exception => e
      puts "Failed in the bson decoding: #{e}"
      return nil
    end
    if decoded_uuid
      decoded_uuid
    end
  end