将txt文件的全文存储到mongodb中

2024-03-05

我创建了一个 python 脚本,可以自动执行将 PDF 转换为 txt 文件的工作流程。我希望能够在 MongoDB 中存储和查询这些文件。我需要将 .txt 文件转换为 JSON/BSON 吗?我应该使用像 PyMongo 这样的程序吗?

我只是不确定这样一个项目的步骤是什么,更不用说有助于实现这一目标的工具了。

我看过这个帖子:如何在 Mongodb 中添加文本文件? https://stackoverflow.com/questions/13081660/how-can-one-add-text-files-in-mongodb,这让我觉得我需要将文件转换为 JSON 文件,并可能集成 GridFS?


如果您使用驱动程序,则不需要对其进行 JSON/BSON 编码。如果您使用 MongoDB shell,则在粘贴内容时需要担心它。

您可能想使用Python MongoDB 驱动程序 http://api.mongodb.org/python/current/index.html:

from pymongo import MongoClient

client = MongoClient()
db = client.test_database  # use a database called "test_database"
collection = db.files   # and inside that DB, a collection called "files"

f = open('test_file_name.txt')  # open a file
text = f.read()    # read the entire contents, should be UTF-8 text

# build a document to be inserted
text_file_doc = {"file_name": "test_file_name.txt", "contents" : text }
# insert the contents into the "file" collection
collection.insert(text_file_doc)

(未经测试的代码)

如果您确保文件名是唯一的,您可以设置_id文档的属性并像这样检索它:

text_file_doc = collection.find_one({"_id": "test_file_name.txt"})

或者,您可以确保file_name如上所示的属性已被索引并执行以下操作:

text_file_doc = collection.find_one({"file_name": "test_file_name.txt"})

您的另一个选择是使用 GridFS,尽管通常不建议将其用于小文件。

有一个启动器here http://api.mongodb.org/python/current/examples/gridfs.html适用于 Python 和 GridFS。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将txt文件的全文存储到mongodb中 的相关文章

随机推荐