本文介绍了通过蒙戈shell脚本读取的图像文件转换成MongoDB的文档的二进制领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取图像文件转换成MongoDB的文档的二进制字段从蒙戈外壳。我可以在Java与MongoDB的Java驱动程序做到这一点。不过,我希望能够从蒙戈壳蒙戈脚本来完成。这可能吗?

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:\\蒙戈\\ BIN>蒙戈--shell myscript.js

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

在这里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")**)
                  } );

由于是,使用猫()方法给出了InternalError该:缓冲区太小(匿名):1,因为猫()仅供读取文本文件

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?

推荐答案

我不知道的方式直接从蒙戈外壳读一个二进制文件。不过,我知道的一种方式做到这一点,如果你愿意从外部处理文件并将其转换为的base64 。请注意,您必须反正进行一些转换,因为据我所知,你不能原始二进制数据存储MongoDB的内部

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.

在Linux中,我尝试以下,并验证它的工作原理:

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

这篇关于通过蒙戈shell脚本读取的图像文件转换成MongoDB的文档的二进制领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 12:03