14

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?

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145

3 Answers3

25

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.

XenoN
  • 984
  • 1
  • 10
  • 23
15

You want to use db.fs.delete(_id); instead.

Update Sorry, that apparently doesn't work from the shell, only through the driver. GridFS is a specification for storage implemented by the drivers. Looks like it doesn't have much built-in functionality from the shell, as such.

Update 2 There is also a command line tool, mongofiles (http://www.mongodb.org/display/DOCS/GridFS+Tools), which allows you to delete files by name. mongofiles delete <filename>. It comes with a warning that it will delete all of the files by that name, so it's not as granular as by id.

Eve Freeman
  • 32,467
  • 4
  • 86
  • 101
  • Ah I see. Sadly, I can't use mongofiles because I only have the ID of the file I want to delete. Do you foresee any problems I would get by deleting the matching chunks myself? – Alex Turpin Jan 09 '12 at 21:04
  • 4
    Do you need to do this through the shell? Why not connect with a driver in your language of choice? And no, as far as I know it would be ok to do something like `db.fs.chunks.remove({files_id:my_id});` and then `db.fs.files.remove({_id:my_id});` – Eve Freeman Jan 09 '12 at 21:13
  • I would have preferred doing it from the shell but I'll use a language with a driver. Thanks! – Alex Turpin Jan 09 '12 at 21:13
3
mongofiles --host localhost:30000 --db logo delete logo_susan1225.png

refer to this page: http://docs.mongodb.org/manual/reference/program/mongofiles/#bin.mongofiles

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111