如何使用pymongo在我的GridFS上存储自定义元数据?

时间:2014-04-16 11:25:57

标签: python mongodb pymongo gridfs bson

在过去的几天里,我一直在尝试为我在GridFS中插入的文件添加一些自定义元数据。

插入是在没有任何元数据的情况下正确完成的,但是我所有尝试添加自定义元数据(使用BSON.encode(),json_utils,作为json本身)都插入但不正确,如下所示:

One of the incorrect isertions

(这只是众多尝试之一)

并且,如果我尝试从MongoVue中删除它,我会收到以下错误:

Error in deleting file - Screenshot.C1.P94.74CB87859F8929FA289AAC1AF448FDE6121137C0.png
Unable to cast object of type 'MongoDB.Bson.BsonString' to type    'MongoDB.Bson.BsonDocument'.
Type: System.InvalidCastException
Stack:    at MongoDB.Bson.BsonValue.get_AsBsonDocument()
at MongoDB.Driver.GridFS.MongoGridFSFileInfo.CacheFileInfo(BsonDocument fileInfo)
at MongoDB.Driver.GridFS.MongoGridFSFileInfo.Refresh()
at MongoDB.Driver.GridFS.MongoGridFSFileInfo.get_Exists()
at MongoDB.Driver.GridFS.MongoGridFSFileInfo.Delete()

看起来我必须将元数据作为BSON文档插入,但我发现无法这样做。

有什么想法吗?

提前多多感谢!

1 个答案:

答案 0 :(得分:1)

以下对我来说很好:

file_id = grid_fs.put(file_from_disk, 
  filename="feature_arrays.npz", 
  comment="compressed numpy arrays", 
  meta="this is some meta")

我认为这也适用于dict而不是“meta”或其他任何字符串。您还可以使用以下关键字存储所有元数据:

file_id = grid_fs.put(file_from_disk, 
  meta1=link_to_img, 
  meta2=author,
  meta3=datetime.now())

据我所知,你在使用python驱动程序时不应该担心BSON。