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

How does one remove an array element by key?

The docs seem to indicate it's as simple as identifying the key by name, but this doesn't seem to work.

For example, with the images array below, and a key of 59db1c3654819952005897, I'm unable to remove the element (the code below produces no errors, but doesn't remove anything):

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

Here is the data structure:

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

The problem you're having is because your pull query is looking for a document where the value of images is equal to 59db1c3654819952005897 and in your case, it's not true.

Even if you try to perform a find query with the params you've specified, it will return no result:

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

To solve it, you must find a query that will be able to retrieve your document, which would be the following:

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

Now to update your $pull query:

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

So in PHP it would be:

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

In other words, it's going to pull in the images array if 59db1c3654819952005897 exists inside for the document with an _id of value 34.