1

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
Zazz
  • 381
  • 2
  • 12
  • 1
    Does this https://stackoverflow.com/questions/31844321/how-to-convert-a-base64-encoded-string-to-uuid-format solve your problem? – Jan Vítek Jun 05 '23 at 09:52
  • @JanVítek That solved it, thank you so much! :) I actually tried using unpack() before after seeing a similar thread but it didn't work - the problem was that I didn't have the "first_unpack"-part – Zazz Jun 05 '23 at 12:04

1 Answers1

0

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
Zazz
  • 381
  • 2
  • 12