【问题标题】:How to add a field in fs.chunks collection in MongoDB using Pymongo?如何使用 Pymongo 在 MongoDB 的 fs.chunks 集合中添加一个字段?
【发布时间】:2018-10-22 10:47:42
【问题描述】:

我正在使用 GirdFs 将本地目录中的图像存储到 MongoDB 集合。

from pymongo import MongoClient
from imutils import paths
import gridfs

client = MongoClient("127.0.0.1", 27017)
db = client.dbs 
fs = gridfs.GridFS(db)


imagePaths = list(paths.list_images("images"))

for i, imagePath in enumerate(imagePaths):
    name = imagePath.split(os.path.sep)[-2]  # to get the name of the directory
    fs.put(open(imagePath, 'rb'))

上面的代码创建了两个集合fs.files和fs.chunks。 它在 fs.files 中创建包含字段的元数据

  • _id
  • md5
  • 块大小
  • 长度
  • 上传日期

所以在我的图像文件夹中有子文件夹,我想将子文件夹的名称(存储在 name 变量中)保存到 fs.files。

我怎样才能做到这一点?

我检查了put 方法here 的文档。它需要数据参数和 **kwargs。我不知道这是否有助于添加新字段,因为没有可用的详细信息。

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    Gridfs Specification 中描述的任何文件级选项都可以作为关键字参数传递。

    例如,你可以这样设置文件名

    fs.put(open(imagePath, 'rb'), filename="foo")
    

    文件文档规范中不可用的任何其他字段都可以存储在文件文档元数据字段中。
    元数据字段可以保存任何类型,因此您在此处存储的任何内容都由您自己处理。

    fs.put(open(imagePath, 'rb'), metadata={"subfolder": "foo-subfolder"})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-22
      • 2016-05-16
      • 2018-12-03
      • 1970-01-01
      • 2015-09-06
      • 2020-12-07
      • 2018-03-16
      • 1970-01-01
      相关资源
      最近更新 更多