Read image file into a MongoDB document's binary field via mongo shell script

后端 未结 1 1784
無奈伤痛
無奈伤痛 2021-01-15 13:46

I would like to read an image file into a MongoDB document\'s binary field from mongo shell. I can do this in Java with MongoDB Java driver. However, I would like to be ab

相关标签:
1条回答
  • 2021-01-15 14:41

    I don't know of a way to read a binary file directly from the Mongo shell. However, I do know of a way to do it if you are willing to externally process the file and convert it to base64. Note that you have to perform some conversion anyway, since afaik, you cannot store raw binary data inside MongoDB.

    On Linux, I tried the following and verified it works:

    # Extract 1M random bytes, convert it to base64, and store it as /tmp/rrr
    $ head -c 10000000 /dev/random | base64 > /tmp/r
    
    $ mongo
    > var r = cat ('/tmp/r')                # Reads into r BUT then terminates it with a NL
    > var rr = r.substring (0, r.length-1)  # Remove the newline
    > var p = BinData (0, rr)               # bring it into p
    
    0 讨论(0)
提交回复
热议问题