开发者

How can I delete files (in a transaction-like manner) from MongoDB's GridFS using the Mongo console

I need to delete a bunch of files, stored in Mongo's GridFS that are older than a given date. This implies that I'd need to delete from both fs.files and fs.chunks collections.

I was thinking of writing a function that finds all documents from fs.files that match the search criteria, iterate over them and in the loop delete all documents from fs.chunks that match the files_id value of the corresponding document in fs.files, however, according to the docs:

MongoDB supports atomic operations on single documents. MongoDB does not support traditional locking and complex transactions

which makes me think my suggested approach might not be the correct one.

I know I could use one of the client drivers to manipulate the GridFS directly. For example, using PHP I could implement it like this:

<?php
$grid = $db->getGridFS('fs');

$grid->remove(array(
    "uploadDate" => array(
        '$lt' => new MongoDate(strtotime("2011-02-01 00:00:00"))
    )
));

... however I wish to accomplish this using only the mongo console.

So, what is the preferred way to remove files, matching certain criteria regarding a field in fs.files from both collections, using the mongo console,开发者_运维百科 or a JS file, feeding the console?


Your suggested approach is mostly correct. The only pointer to a file's contents is in fs.files, so if you delete that first and something goes wrong deleting the chunks, at least nothing will be hanging around that could reference those chunks.

To be on the safe side, you could have a background job that goes through the files_id field of the chunks collection (which is indexed, so it should be fast) and makes sure all files_ids match up with docs in the fs.files collection. If they don't and they weren't created relatively recently (you can get the timestamp they were created at from the _id field), you can delete them. (You wouldn't want to delete recently created chunks, in case they are part of a file currently being inserted.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜