mongodb

时间:2017-01-05 14:11:05

标签: c# mongodb mongodb-query mongodb-.net-driver gridfs

我必须在文件中搜索内容。这是在db上传的,如image(bmp,tiff,png)或pdf等。

我正在使用最新版本的Mongodb来存储使用GridFS的图像(png,bmp,jpg)或文档。即以二进制形式存储数据。 MongoDB使用两种方式来存储文档,其中一种是二进制文件,另一种是json。

所以Mongodb没有提供直接搜索图像内容的方法。 另一个是我可以使用OCR,但OCR提供字符串的最终结果所以我必须将其转换为有效的json存储在db中。如果它是我的最后一个选项,那么我将如何将该字符串转换为有效的json格式。

我正在尝试使用以下代码在mongodb中存储文本文件。

// result5.txt is a text file that is result of OCR.        

string text = System.IO.File.ReadAllText("E:\\result5.txt");

var document = BsonSerializer.Deserialize<BsonDocument>(text);

var collection = Database.GetCollection("articles");

collection.Insert(text);

但我收到了错误。

  

MongoCommandException:命令插入失败:错误的类型   文件[0]。期待一个对象,得到一个字符串。

如何在我在db中上传的图像文件中搜索。??

所以任何建议都将不胜感激,请管理员不要关闭此帖的评论谢谢。

以此形式存储的文本数据。 enter image description here

1 个答案:

答案 0 :(得分:1)

只需创建新类以包含OCR结果:

public class OcrContainer
{
    public BsonObjectId Id { get; set; }
    public string OcrResult { get; set;}
}

并将其存储到mongo:

var collection = Database.GetCollection<OcrContainer >("articles");
collection.InsertOne(new OcrContainer {OcrResult = text});

之后你可以搜索你的结果:

collection.Find(x=>x.OcrResult.Contains("bla"))

<强>可是: 你打算用它做什么?在OcrCollection中需要更多属性才能将ocr结果与其他数据连接起来。