【问题标题】:MongoDB/PHP removing a specific array item inside the documentMongoDB/PHP 删除文档中的特定数组项
【发布时间】:2014-09-02 19:34:06
【问题描述】:

现在,我的收藏中有一个文档,我想在点击时删除它,它们是发布文档中的 cmets。

结构如下:

{
    "_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')

我尝试了几种解决方案,

-第一个:

$collection->update( array("_id" => $_GET['post']), array( '$unset' => 
 array("comments" => array("_id" => $_GET['id']))) );

这个刚刚删除了我在 cmets 数组中的所有 cmets。

-第二:

$delete = array('$pull' => array("comments" => array( '_id' => $_GET['id'])));
$collection->update(array('_id' => $_GET['post']), $delete);

几乎没有做任何事情,奇怪的是,这应该有效,对吧?

-第三种解决方案:

$collection->remove( array('_id' => $_GET['post'], 'comments._id' => $_GET['id']));

实现这一目标的正确方法是什么?我在这方面做了很多努力,甚至实现了一些聚合查询,但没有成功。

【问题讨论】:

  • 如何在php中添加_id到嵌入文档(cmets)

标签: php mongodb mongodb-query


【解决方案1】:

要从数组中删除元素,请使用$pull 运算符。这需要一个“查询”表达式来识别您要删除的元素:

$collection->update( 
    array("_id" => $_GET['post']),
    array( '$pull' => 
        array(
            "comments" => array(
                "_id" => new MongoId( $_GET['id'] )
            )
        )
    )
);

$pull 的“查询”部分作用于指定数组的各个元素,因此任何符合条件的元素都将从数组中删除。但同样重要的是,您的请求参数是一个“字符串”,因此您需要将其转换为实际的 ObjectId 值,您可以使用驱动程序中的 MongoId 类在 PHP 中进行转换。

注意 Modern driver releases 使用 MongoDB\BSON\ObjectId 作为将“字符串十六进制值”转换为实际 ObjectId 表示的正确方法。

【讨论】:

  • 谢谢,我多次尝试了上面列出的解决方案,但忘记添加新的 MongoId() 指标,而是以原始方式放置 $_GET['id'] ,所以它没有从阵列中拉出任何东西。干杯!
猜你喜欢
  • 1970-01-01
  • 2017-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多