'How to retrieve files from MongoDB (no GridFS)?

I have a file (can be any type) which I want to store in Mongo, so I converted it to binary in order to store it in a Mongo collection. The code I use to take the original file and convert it to binary is this.

with open(os.path.join("temp_client_files", packaging_specs_file),"wb") as fh: 
        bindata = bson.binary.Binary(packaging_specs_file.getbuffer())
        #store bindata in a field of a document in my collection

I basically create bindata and then insert a document in my collection which has a field where bindata is stored. In Mongo, the document's field's value looks like something like this: Binary('iVBORw0KGgoAAAANSUhEUgAAAS0AAAEtCAYAAABd4zbuAAAAAXNSR0IArs4c6QAAFSVJREFUeF7t3U/IbddZx/E04VqapqRiewsa...', 0)

My question is: how can I retrieve the field's value (so the binary object above) and store it as a file in my local folder? When I use pymongo's find() to get the document and access the field, I get a very long string that looks like

b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01-\x00\x00\x01-\x08\x06\x00\x00\x00]\xe36\xee\x00\x00\x00\x01sRGB\x00\xae\xce\x1c\xe9\x00\x00\x15%IDATx^\xed\xddO\xc8m\xd7Y\xc7\xf14\xe1Z\x9a\xa6\xa4b{\x0b\x1a\xaa\xa5\xe8 h\x0b\xd1 ... ...

I am unsure how to go from that string to having the represented file (which can be any format, like pdf, or jpg) downloaded locally

The workflow

  • A file (any format) is uploaded in the front-end
  • In the backend, it gets converted to binary and uploaded to mongo as shown above
  • I now want to get it from mongo and turn the binary back to the file I started with (e.g. a pdf, or a jpg) How do I do that?


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source