简体   繁体   English

在PHP中删除MongoDB GridFS中的多个文件

[英]Delete multiple files in MongoDB GridFS in PHP

I am using MongoDB and GridFS in PHP , and trying to figure out how to delete multiple files by the _id . 我在PHP使用MongoDBGridFS ,并试图找出如何通过_id删除多个文件。

Here is the code I have: 这是我的代码:

 $ids = array("50401f40ff558cec38000061", "62401f40ff558cec38000072", "73401f40ff558cec38000083");
 $mongo_ids = array();
 foreach($ids as $id) {
    $mongo_ids[] = new MongoId($id);
 }

 $mongo_grid_fs->remove(array("_id" => $mongo_ids));

Any idea what I am doing wrong? 知道我在做什么错吗?

This impossible to do with a single request due to the way that GridFS actually works. 由于GridFS的实际工作方式,单个请求不可能做到这一点。

You have two collections: 您有两个集合:

  • Files 档案
  • Chunks 大块

Inorder to delete a GridFs file you must query BOTH of these table. 为了删除GridFs文件,您必须查询这两个表。 As such the remove() function actually calls the chunk collection and then removes the file from the files collection. 这样,remove()函数实际上会调用块集合,然后从文件集合中删除文件。

Since MongoDB cannot, fundamentally, query two collections in one request (joined deleted basically) you must send a delete request per file to delete otherwise you will have left over chunks taking up space in your chunks collection. 由于MongoDB从根本上不能在一个请求中查询两个集合(基本上是联接删除),因此您必须为每个文件发送一个删除请求以进行删除,否则您将剩下大块,占用大块集合中的空间。

As such, taking this into consideration @ToddMoses answer is the correct one. 因此,考虑到@ToddMoses答案是正确的答案。

You can of course use: http://www.php.net/manual/en/mongogridfs.remove.php but I believe it does exactly the same thing, just abstracted so your query should have been: 您当然可以使用: http : //www.php.net/manual/en/mongogridfs.remove.php,但我相信它做的完全一样,只是抽象了一下,所以您的查询应该是:

$mongo_grid_fs->remove(array("_id" => array('$in' => $mongo_ids)));

First, use MongoDB::lastError() to find out what is going wrong. 首先,使用MongoDB :: lastError()找出问题所在。 MongoGridFS::remove won't present you with a message if it fails. 如果MongoGridFS :: remove失败,则不会向您显示消息。 DO something like this: 做这样的事情:

$errorArray = $db->lastError();
var_dump($errorArray);

It appears the problem is that you are not setting the criteria properly. 看来问题在于您没有正确设置标准。 The easiest thing to do is just use Delete instead of Remove since Delete takes an ID as its only parameter: 最简单的方法是使用Delete而不是Remove,因为Delete将ID作为唯一参数:

public bool MongoGridFS::delete ( mixed $id )

This deletes a file from the database whereas remove deletes files from the collection. 这将从数据库中删除文件,而删除则从集合中删除文件。 Since you are looping anyway, you can do something like this: 由于无论如何都在循环,因此您可以执行以下操作:

foreach($ids as $id) {
    $mongo_grid_fs->delete($id);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM