MongoDB remove GridFS objects from shell

Alex Turpin picture Alex Turpin · Jan 9, 2012 · Viewed 15.6k times · Source

I have files stored in a MongoDB using GridFS. I need to remove some of those files by ID, from the JavaScript shell. I need to remove a single file using it's ID. I figured I could just do this:

db.fs.files.remove({_id: my_id});

This works to some extent; it removes the file from the fs.files collection but does not remove the chunks itself from the fs.chunks collection. The reason I know that is because I check the length of both collections before and after in RockMongo.

I could go through the chunks and remove those that are referring to that file, but is there a better, built-in way of doing that?

Answer

XenoN picture XenoN · Nov 19, 2013

You can delete gridFS file by deleting both chunks and files from shell. for example

db['fs.chunks'].remove({files_id:my_id});
db['fs.files'].remove({_id:my_id});

Those commands will do such trick.