Image 将图像文件读入MongoDB文档';通过mongo shell脚本创建二进制字段

Image 将图像文件读入MongoDB文档';通过mongo shell脚本创建二进制字段,image,file-io,binary,mongo-shell,Image,File Io,Binary,Mongo Shell,我想从MongoShell将一个图像文件读入MongoDB文档的二进制字段。我可以用MongoDB Java驱动程序在Java中实现这一点。但是,我希望能够使用来自MongoShell的mongo脚本。这可能吗 例如,我想这样做: D:\mongo\bin>mongo--shell myscript.js 其中myscript.js如下所示: conn = new Mongo(); db = conn.getDB("mydb"); db.mycoll.remove(); db.mycoll.in

我想从MongoShell将一个图像文件读入MongoDB文档的二进制字段。我可以用MongoDB Java驱动程序在Java中实现这一点。但是,我希望能够使用来自MongoShell的mongo脚本。这可能吗

例如,我想这样做:

D:\mongo\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 To small(anon):1”,因为cat()仅用于读取文本文件

我应该使用哪种方法/函数来代替cat(),以实现此功能?
这可以在mongo shell中完成吗?

我不知道如何直接从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

我不知道如何直接从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

谢谢,拉姆。但这对我不起作用,因为这些是要存储在MongoDB文档字段中的图像文件。数据需要保持不变,以便可以使用java驱动程序读取和显示。正如我在原始问题中提到的,我已经验证了我可以使用java在MongoDB中存储和检索这些.jpg文件。此外,在Windows 7中转换为base64可能会增加一个额外的步骤,我无法在mongo脚本中运行。答案不适用于所问问题。谢谢,Ram。但这对我不起作用,因为这些是要存储在MongoDB文档字段中的图像文件。数据需要保持不变,以便可以使用java驱动程序读取和显示。正如我在原始问题中提到的,我已经验证了我可以使用java在MongoDB中存储和检索这些.jpg文件。此外,在Windows7中转换为base64可能会增加一个额外的步骤,我无法在mongo脚本中运行该步骤。答案不适用于所问问题。