2016-11-08 88 views
0

我是mongodb中的新成员。我想从集合中删除特定的文档,但在没有任何语法错误的情况下无法删除。使用PHP删除Mongodb中的特定文档

这里是show_post.php

<?php 
    $connect = new Mongoclient(); 
    $db = $connect -> post; 

<table width="50%" border="1"> 
    <tr> 


    <th>#</th> 
    <th>Title</th> 
    <th>description</th> 
    <th colspan="2">Action</th> 
    </tr> 
    <?php $result = $db->blogs->find();?> 
    <?php foreach ($result as $row) : ?> 
     <tr> 
     <td><?php echo $row["_id"]; ?></td> 
     <td><?php echo $row["title"]; ?></td> 
     <td><?php echo $row["description"]; ?></td> 

     <td><a href="delete_post.php?id=<?php echo $row['_id'] ?>">Delete</a></td> 
     <td> <a href="edit_post.php?id=<?php echo $row['_id'] ?>">Update</a></td> 

     </tr> 
     <?php endforeach?> 

</table> 

这里是delete_post.php

 

     $id=$_GET['id']; 
     $var = array("_id"=>$id); 

     $del =$db->blogs->remove($var); 
      if(!$del){ 

      echo "not deleted"; 
      }else { 
      header("location:show_post.php"); 
      exit(); 
      } 
      ?> 



+0

尝试查询您的ID,看你是路过什么ID删除功能。记住,如果你试图删除一个不存在的对象,mongoDB不会抛出任何异常。 –

回答

0

这可能是因为你正在过_idfind()方法的字符串表示:

<td><a href="delete_post.php?id=<?php echo $row['_id'] ?>">Delete</a></td> 

由于MongoDB PHP版本> = 1.0.0,find()应返回MongoDB\BSON\ObjectID对象。如果你使用echo这个变量,它会返回字符串表示。

你可以做的是将其转换回为对象:

$var = array("_id"=>new MongoDB\BSON\ObjectID($id));