3

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 able to do with a mongo script from mongo shell. Is this possible?

For example, I would like to do this:

D:\mongo\bin> mongo --shell myscript.js

where myscript.js is as follow:

conn = new Mongo();
db = conn.getDB("mydb");
db.mycoll.remove();
db.mycoll.insert( { name : "LCD monitor",
                    thumbnail : Binary(0, **cat("D:\\images\\lcdmonitor.jpg")**)
                  } );

As is, the use of cat() method gives "InternalError: buffer too small (anon):1", as cat() is for reading text file only.

Which method / function in place of cat() should I use to make this work? Can this be done in the mongo shell at all?

das-g
  • 9,718
  • 4
  • 38
  • 80
Roy Batty
  • 31
  • 1
  • 2

1 Answers1

-1

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
Ram Rajamony
  • 1,717
  • 15
  • 17
  • 2
    Thanks, Ram. But this would not work for me, as these are image files to be stored in MongoDB document's field. The data need to be unchanged so it can be read back out and display using java driver. As I mentioned in my original question, I have already verified that I can store and retrieve these .jpg files to / from MongoDB using java. Furthermore, conversion to base64 in Windows 7 probably add an extra step coming / going which I can't run in a mongo script. – Roy Batty Jun 09 '13 at 04:34
  • Answer is not applicable to question asked. – Will Apr 30 '19 at 21:18