PHP MongoDB \ Client updateOne向现有文档数组添加新字段

时间:2019-07-01 20:51:14

标签: php arrays mongodb

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

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

$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. 可能两者兼有,从一开始我就错了。

请欣赏任何见解或建设性的批评,请避免发火。

1 个答案:

答案 0 :(得分:0)

这是我最后用来使它按我想要的方式工作的代码。

只需设置您的字段名称和值,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,
    ]
);