通过mongo shell脚本将图像文件读入MongoDB文档的二进制字段

时间:2013-06-08 21:55:17

标签: image file-io binary mongo-shell

我想从mongo shell将图像文件读入MongoDB文档的二进制字段。我可以使用MongoDB Java驱动程序在Java中执行此操作。但是,我希望能够使用mongo shell的mongo脚本。这可能吗?

例如,我想这样做:

d:\蒙戈\ BIN> mongo --shell myscript.js

其中myscript.js如下:

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

因为使用cat()方法会给出“InternalError:buffer too small(anon):1”,因为cat()仅用于读取文本文件。

我应该使用哪种方法/函数代替cat()来完成这项工作? 这可以在mongo shell中完成吗?

1 个答案:

答案 0 :(得分:-1)

我不知道直接从Mongo shell读取二进制文件的方法。但是,如果您愿意从外部处理文件并将其转换为base64,我确实知道一种方法。请注意,您必须执行一些转换,因为afaik,您无法在MongoDB中存储原始二进制数据。

在Linux上,我尝试了以下操作并验证它是否有效:

# 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