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

我想从 mongo shell 中将图像文件读取到 MongoDB 文档的二进制字段中。我可以使用 MongoDB Java 驱动程序在 Java 中执行此操作。但是,我希望能够使用来自 mongo shell 的 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 too 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

https://stackoverflow.com/questions/17004242/

相关文章:

arrays - 重命名 MongoDB 数组中嵌入文档中的字段不起作用

python - 在python多处理中实现Ctrl+C取消

node.js - Mongo降序排序

vbscript - 带参数的 Shell.Run

python - 在 python 中加载 JSON 作为实际对象,而不是 dict

c# - 在 C#/.NET 中逐笔更新到烛台/OHLC 数据

three.js - 在 three.js 中显示数千张图片

jsp - JSTL 自定义标签变量替换

visual-studio-2010 - Visual-Studio 中 lex 和 yacc 的语

django - 在 Django 中的多个字段上进行关键字搜索