如何在MongoDB中按键删除特定的子元素

时间:2017-10-13 19:13:44

标签: php mongodb

如何按键删除数组元素?

文档似乎表明它与按名称识别密钥一样简单,但这似乎不起作用。

例如,对于下面的图像数组和59db1c3654819952005897的键,我无法删除该元素(下面的代码不会产生任何错误,但不会删除任何内容):

updateOne(['_id' => 34], ['$pull' => ["images" => "59db1c3654819952005897"]])

这是数据结构:

"_id" : 34,  
"images": [
    {
        "59db1c3654819952005897": {
            "name": "1024x1024.png",
            "size": "19421",
            "sort": 2
        }
    },
    {
        "59db1c3652cda581935479": {
            "name": "200x200.png",
            "size": "52100",
            "sort": 3
        }
    }
]

1 个答案:

答案 0 :(得分:1)

您遇到的问题是因为您的pull查询正在查找images的值等于59db1c3654819952005897的文档,而在您的情况下,它不是真的。< / p>

即使您尝试使用您指定的参数执行find查询,也不会返回任何结果:

db.getCollection('collection').find({
    'images': '59db1c3654819952005897'
});

要解决此问题,您必须找到一个能够检索文档的查询,其中包括以下内容:

db.getCollection('collection').find({
    'images': {
        '59db1c3654819952005897': {
            '$exists': true
        }
    }
});

现在更新您的$pull查询:

db.getCollection('collection').updateOne({'_id': 34}, {
    '$pull': {
        'images': {
            '59db1c3654819952005897': {
                '$exists': true
            }
        }
    }
});

所以在PHP中它将是:

$id = '59db1c3654819952005897';
updateOne(['_id' => 34], ['$pull' => [
    'images' => [
        $id => [
            '$exists' => true
        ]
    ]
]]);

换句话说,如果images存在59db1c3654819952005897数组_id,那么它会引入34数组。