我正在努力更新文档并将新元素(字段)添加到现有数组中,而不会在更新时丢失数组元素。
这是我的代码,如果它不存在(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),
],
我注意到有“$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 ...
我知道以下几点:
它可能是我的文档,因为它不是致命错误所抱怨的正确数组。
这可能是我的“findOneAndUpdate”格式,而我没有正确地这样做。
可能两者兼而有之,我从一开始就错了。
任何见解或建设性的批评表示赞赏,只是不要火焰,请。
慕码人8056858