1
我希望你們能幫助我這個:如何正確轉換的MongoDB BSON到PHP對象
首先第一件事情 - 我使用以下版本/庫:
- PHP:PHP 7.0。 3-1〜dotdeb + 8.1
- mongodb的版本=> 1.1.2
- 蒙戈PHPLibrary(https://github.com/mongodb/mongo-php-library/)
我試圖噸o將BSON數組轉換成數據庫,以便在我的項目中使用。
正如我所瞭解的MongoDB的一個大的機會是在一個集合中有不同的有組織的數據。 像在本例中(其中只有一個對象具有 「描述」 的標籤:
JSON文獻:
{
enumbers ":[ {
"id": "84",
"enumber": "E 472 b",
"name": "Milchs\u00e4ureester von Mono- und Diglyceriden von Speisefetts\u00e4uren"
}, {
"id": "198",
"enumber": "E 407",
"name": "Carrageen",
"description": "Testdescription",
}, {
"id": "293",
"enumber": "E 941",
"name": "Stickstoff"
}]
}
我訪問與下面的代碼數據庫:
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$collection = new MongoDB\Collection($manager, "test", "items");
$document = $collection->findOne(["id" => '5']);
$product= new Product($document);
廠細直到這裏。
use MongoDB\Model\BSONArray;
use MongoDB\Model\BSONDocument;
class Product
public function __construct(BSONDocument $data)
{
foreach ($data as $part){
try{
$this->setId($part->id);
$this->setEnumber($part->id);
$this->setName($part->name);
--------------------------------------
$this->setDescription($part->description);
--------------------------------------
}catch (\Exception $e){
echo $e;
}
}
echo "-------------------------------------------------".PHP_EOL;
}
現在「$ this-> setDescription($ part-> description); 「拋出異常:
其中沒有定義」描述「標記。
其實我希望它返回空它不存在的地方。
我如何正確捕捉這些數據集可能有或沒有這個標籤?
希望你能幫助我&感謝閱讀:)