5

I have an image with the following metadata:

> db.fs.files.find().pretty()
{
    "_id" : ObjectId("4576874577342672346"),
    "chunkSize" : 262144,
    "user_name" : "my name",
    "filename" : "image.jpg",
    "length" : 7103,
    "uploadDate" : ISODate("2014-01-23T13:31:48.155Z"),
    "user_email" : "email@email.com",
    "md5" : "1234567890"
}
>

I want to delete the image from Python (PyMongo).

The documentation on delete() seems to stipulate that the only accepted parameter in the delete() function is the file_id:

http://api.mongodb.org/python/current/api/gridfs/#gridfs.GridFS.delete

Programmatically, I have the following values available that can be matched in the files metadata:

  • user_name
  • filename
  • user_email

How do I either:

  • Get the file_id (through use of the above values if necessary) or
  • Delete the file based on metadata fields other than file_id?

Additionally, I am only currently testing with single chunk files, if interacting with larger files in the future will deleting by file_id or other metadata remove all associated chunks as well?

1 Answer 1

4

Here's something I just tried without thinking if it's necessary or the best way to do it, but it works.

So programatically I could have the _id available from querying on the files metadata:

Python Shell:

>>> import pymongo
>>> import os
>>> hostname = os.environ['OPENSHIFT_MONGODB_DB_URL']
>>> conn = pymongo.MongoClient(host=hostname)
>>> db = conn.grid_files
>>> collection = db.fs.files
>>> result = collection.find_one({"user_email":"email@email.com","name":"my name","filename":"image.jpg"})
>>> result['_id']
ObjectId('52e119c47091447a86891d98')

# now use the _id to delete the file
>>> files_id = result['_id']
>>> import gridfs
>>> fs = gridfs.GridFS(db)
>>> fs.delete(files_id)
1
  • 2
    Yes, this approach works fine. GridFS is really just a convention that maps to normal MongoDB collections (by default fs.files with a 1:many relationship to fs.chunks). Since you are using the fs.delete(_id) method provided by the GridFS module, it will delete all associated data from both collections.
    – Stennie
    Jan 24, 2014 at 4:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.