如果您使用驱动程序,则不需要对其进行 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。