【问题标题】:PHP MongoDB\Client updateOne add new field to existing document arrayPHP MongoDB\Client updateOne 将新字段添加到现有文档数组
【发布时间】:2019-11-12 12:03:24
【问题描述】:

我正在努力更新文档并将新元素(字段)添加到现有数组中,而不会在更新时丢失数组元素。

这是我的代码,如果新文档不存在,则将其插入到集合中(更新插入):

$updateResult = $collection->findOneAndUpdate(
            [
                'recording-id' => $out['recording']->id
            ],
            ['$set'  => [
                'release'            =>    [
                    'id'            => $out['release']->id, 
                    'title'         => $out['release']->title,
                    'date'          => $out['release']->date,
                    'country'       => $out['release']->country
                ],
                'artist'            => [
                    'id'            => $out['artist']->id,
                    'name'          => $out['artist']->name,
                ],
                'recording'         => [
                    'id'            => $out['recording']->id,
                    'title'         => $out['recording']->title,
                    'score'         => $out['recording']->score,
                    'length'        => $out['recording']->length,
                    'release-count' => count($out['recording']->releases),
                ],
                'release-group'     => [
                    'id'            => $out['release-group']['id'],
                    'title'         => $out['release-group']['title'],
                    'first-release-date'=>$out['release-group']['first-release-date'],
                    'primary-type'  => $out['release-group']['primary-type'],
                    'musicbrainz'   => $out['release-group']['musicbrainz'],
                    'url-rels'      => $out['release-group']['url-rels'],
                    'coverart'      => $out['release-group']['coverart']
                ],
                'execution'         => [
                    'firstfind'     => $out['execution']->time
                ]


            ]
        ],
        ['upsert'           => true,
        'projection'        => 
        [ 
            '_id'               => 0,
             'release'          => 1, 
             'artist'           => 1,
             'recording'        => 1,
             'release-group'    => 1,
             'execution'        => 1


        ],
        'returnDocument'    => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER,
        ]
    );

所以现在我在集合中有一个现有文档:

{
    "_id" : ObjectId("5d1a6aaf5ecc8001ee858f6c"),
    "recording-id" : "d0d439f9-5324-4728-8706-2da39adb89c5",
    "artist" : {
        "id" : "9d97b077-b28d-4ba8-a3d9-c71926e3b2b6",
        "name" : "Gordon Lightfoot"
    },
    "recording" : {
        "id" : "d0d439f9-5324-4728-8706-2da39adb89c5",
        "title" : "Sundown",
        "score" : 100,
        "length" : 184000,
        "release-count" : 2
    },
    "release" : {
        "id" : "0c008d76-2bc9-44a3-854b-0a08cde89337",
        "title" : "All Live",
        "date" : "2012-04-24",
        "country" : "CA"
    },
    "release-group" : {
        "id" : "0a5d5f33-8e9d-4fa4-b622-a95e4218a3c4",
        "title" : "All Live",
        "first-release-date" : "2012-04-24",
        "primary-type" : "Album",
        "musicbrainz" : "https://musicbrainz.org/release-group/0a5d5f33-8e9d-4fa4-b622-a95e4218a3c4",
        "url-rels" : "https://musicbrainz.org/ws/2/release-group/0a5d5f33-8e9d-4fa4-b622-a95e4218a3c4?inc=url-rels&fmt=json",
        "coverart" : null
    }
}  

现在,我想更新此文档,并将新字段添加到数组中。新字段将添加到某些字段。 这是执行此操作的代码:

$collection         = (new MongoDB\Client)->stream->musicbrainz;
    $updateResult = $collection->updateOne(
        [
            'recording-id' => $out['recording']['id']
        ],
        ['$addToSet'  => [
            'artist'            => [
                'wikiQiD'       => $out['artist']['qid'],
                'wiki-extract'  => $out['artist']['wiki-extract'],
                'wiki-pageid'   => $out['artist']['pageid'],
            ],
            'release-group'     => [
                'wikiQiD'       => $out['release-group']['qid'],
                'wiki-extract'  => $out['release-group']['wiki-extract']
            ]
        ]
    ],

    [
        'upsert'           => true,
        'returnDocument'    => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER,
    ]
);

我注意到有“$addToSet”和“$push”命令,可以帮助了解这两个命令之间的区别。

如果文档中没有要更新的字段,$push 会添加数组 以值作为元素的字段。

$addToSet 运算符向数组添加一个值,除非该值是 已经存在,在这种情况下 $addToSet 对该数组不做任何事情。

我做了一些谷歌搜索,并阅读了 MongoDB/Client UpdateOne 函数,但似乎找不到将这些字段附加到现有数组的方法。

我得到的错误是:

Fatal error: Uncaught MongoDB\Driver\Exception\BulkWriteException: The field 'artist' must be an array but is of type object in document {_id: ObjectId('5d1a6aaf5ecc8001ee858f6c')} in ...

我知道以下几点:

  1. 它可能是我的文档,因为它不是致命错误所抱怨的正确数组。
  2. 这可能是我的 `findOneAndUpdate' 格式,而我没有正确处理。
  3. 可能两者兼而有之,而我从一开始就错了。

感谢任何见解或建设性的批评,请不要火上浇油。

【问题讨论】:

    标签: php arrays mongodb


    【解决方案1】:

    这是我最终用来让它做我想做的事情的工作代码。

    只需设置字段名称和值,mongo 将更新找到的记录,将其替换为发送给它的数组。不需要推什么。

    function firstFindMongoUpdate($out) {
    $collection         = (new MongoDB\Client)->stream->musicbrainz;
    $updateResult = $collection->findOneAndUpdate(
            [
                'recording-id'          => $out['recording']->id
            ],
            ['$set'  => [
    
                    'query'             => $out['query'],
    
                    'release'           =>    [
                        'id'            => $out['release']->id, 
                        'title'         => $out['release']->title,
                        'date'          => $out['release']->date,
                        'country'       => $out['release']->country,
                        'label'         => $out['release']->label,
                    ],
                    'artist'            => [
                        'id'            => $out['artist']->id,
                        'name'          => $out['artist']->name, 
                        'wiki'          => $out['artist']->wiki,
                    ],
                    'recording'         => [
                        'id'            => $out['recording']->id,
                        'title'         => $out['recording']->title, // sometimes contains apostophe ie; Bill‘s Love (option ] key)
                        'score'         => $out['recording']->score,
                        'length'        => $out['recording']->length,
                        'release-count' => count($out['recording']->releases)
                    ],
                    'release-group'     => [
                        'id'            => $out['release-group']['id'],
                        'title'         => $out['release-group']['title'],
                        'first-release-date'=>$out['release-group']['first-release-date'],
                        'primary-type'  => $out['release-group']['primary-type'],
                        'musicbrainz'   => $out['release-group']['musicbrainz'],
                        'url-rels'      => $out['release-group']['url-rels'],
                        'coverart'      => $out['release-group']['coverart'],
                        'wiki'          => $out['release-group']['wiki']
                    ],
                    'execution'         => [ 
                        'artistQuery'   => $out['execution']->artistQuery,
                        'recordingQuery'=> $out['execution']->recordingQuery,
                        'time'          => $out['execution']->time
                    ]
    
            ]
        ],
        ['upsert'           => true,
        'projection'        => 
            [ 
            '_id'             => 1,
             'query'          => 1,
             'release'        => 1, 
             'artist'         => 1,
             'recording'      => 1,
             'release-group'  => 1,
             'execution'      => 1
    
            ],
            'returnDocument'    => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER,
        ]
    );
    

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 1970-01-01
      • 2017-09-16
      • 2016-10-16
      • 2020-06-29
      • 2012-10-27
      • 2013-10-26
      • 2015-12-21
      • 2023-02-14
      相关资源
      最近更新 更多