略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: Writes

2024-12-22

Writes

Updating Nested Objects

Suppose we wish to change the name of a comment's author in this document:

{ 
    "_id" : ObjectId("4b06c282edb87a281e09dad9"), 
    "content" : "this is a blog post.",
    "comments" : 
    [
        {
            "author" : "Mike",
            "comment" : "I think that blah blah blah...",
        },
        {
            "author" : "John",
            "comment" : "I disagree."
        }
    ]
}
In order to change an inner field, we use $set (so that all of the other fields are not removed!) with the index of comment to change:
<?php

$blog
->update($criteria, array('$set' => array("comments.1" => array("author" => "Jim"))));

?>

The Positional Operator

The positional operator $ is useful for updating objects that are in arrays. In the example above, for instance, suppose that we did not know the index of the comment that we needed to change, merely that we needed to change "John" to "Jim". We can use $ to do so.

<?php

$blog
->update(
    array(
'comments.author' => 'John'), 
    array(
'$set' => array('comments.$.author' => 'Jim')));

?>
add a note add a note

User Contributed Notes

There are no user contributed notes for this page.

官方地址:https://www.php.net/manual/en/mongo.writes.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3