MongoDB/PHP删除文档中的特定数组项 [英] MongoDB/PHP removing a specific array item inside the document
问题描述
现在,我的收藏夹中有一个文档,我希望在单击时删除该文档,这些文档就是帖子文档中的注释.
Now, I have a document in my collection that I would like to delete on click, and those are comments inside the post document.
结构如下:
{
"_id" : "design-patterns-vs-frameworks",
"title" : "Design Patterns vs Frameworks",
"category" : [
"Frameworks",
" Design Patterns",
" PHP"
],
"date_time" : ISODate("2014-09-02T13:45:29.124Z"),
"description" : "Frameworks vs Design Patterns",
"content" : " Content!",
"author" : "Maciej Sitko",
"comments" : [
{
"_id" : ObjectId("54061528af105b51133c986c"),
"comment" : "ashfklsfsl\r\n",
"author" : "maciejsitko",
"date" : ISODate("2014-09-02T19:06:16.646Z")
},
{
"_id" : ObjectId("5406152caf105b51133c986d"),
"comment" : "lfasdlfsfl",
"author" : "maciejsitko",
"date" : ISODate("2014-09-02T19:06:20.652Z")
}
]
}
完整的删除链接为:
delete.php?post = css-clearfix-explained& id = 540617e3af105b8d133c986a (如您所见,有两个get变量'post'和'id')
delete.php?post=css-clearfix-explained&id=540617e3af105b8d133c986a (as you see two get variables 'post' and 'id')
我尝试了几种解决方案,
I tried several solutions,
-第一个:
$collection->update( array("_id" => $_GET['post']), array( '$unset' =>
array("comments" => array("_id" => $_GET['id']))) );
这只是删除了我的所有评论数组中的评论.
This one just removed all of my comments inside the comments array.
-第二:
$delete = array('$pull' => array("comments" => array( '_id' => $_GET['id'])));
$collection->update(array('_id' => $_GET['post']), $delete);
没有做太多事情,奇怪的是,这应该起作用,对吧?
Did not pretty much do anything, strangely enough, this should work, right?
-第三种解决方案:
$collection->remove( array('_id' => $_GET['post'], 'comments._id' => $_GET['id']));
实现此目标的正确方法是什么?我为此付出了很多努力,甚至实现了一些聚合查询,但都没有解决.
What would be the proper way of achieving this? I struggled on this one a lot, even implementing some aggregation query and it didn't work out.
推荐答案
To remove an element from an array you use the $pull
operator. This takes a "query" expression to identify the element you wish to remove:
$collection->update(
array("_id" => $_GET['post']),
array( '$pull' =>
array(
"comments" => array(
"_id" => new MongoId( $_GET['id'] )
)
)
)
);
$pull
的查询"部分作用于指定数组的各个元素,因此任何与条件匹配的内容都将从数组中删除.但同样重要的是,您的请求参数是字符串",因此您需要将其强制转换为实际的ObjectId
值,您可以使用
The "query" portion of $pull
acts on the individual elements of the array specified, so anything matching the condition will be removed from the array. But also importantly your request parameter is a "string" so you need to cast this as an actual ObjectId
value which you can cast in PHP with the MongoId class from the driver.
注意 现代驱动程序版本使用
MongoDB\BSON\ObjectId
作为转换字符串十六进制值"的正确方法转换成实际的ObjectId
表示形式.
NOTE Modern driver releases use
MongoDB\BSON\ObjectId
as the correct method for casting "string hex value" into an actualObjectId
representation.
这篇关于MongoDB/PHP删除文档中的特定数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!