How to convert MongoDB BSONDocument to valid JSON in PHP? How to convert MongoDB BSONDocument to valid JSON in PHP? json json

How to convert MongoDB BSONDocument to valid JSON in PHP?


I didn't see any answers here and I was having the same issue. I did some research and it appears that when you create a document of MongoDB\Model\BSONDocument there is a bsonSerialize() method. This method will return a stdClass Object which is really the PHP Array Class. According to documentation one can then convert from PHP to BSON and then to JSON.

This is crazy looking, but it works. Here is my example $accountResultDoc is of MongoDB\Model\BSONDocument type.

$json = MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($accountResultDoc))

Results

{  "_id": {    "$oid": "56e1d8c31d41c849fb292184"  },  "accountName": "Michael's Test Company",  "accountType": "Partner",  "subsidiary_id": {    "$oid": "563c3ffbaca6f518d80303ce"  },  "salesforceId": "WERWERWEr2",  "netsuiteExternalId": "56e1d8c31d41c849fb292184",  "suspendBilling": false,  "testAccount": false,  "serviceOrder_ids": null,  "invoice_ids": null}


Another way would be:

json_encode( $bsonDoc->getArrayCopy() );


The BSONDocument object has a jsonSerialize method. Use that:

Example

{"_id" : 12345,    "filename" : "myfile",    "header" : {        "version" : 2,        "registry" : "test",        "serial" : 20080215,        "records" : 17806,        "startDate" : 19850701,        "endDate" : 20080214    },}$connect = new MongoDB\Client('mongodb://yourconnection');$db = $connect->YourDB;$collection = $db->YourCollection;$test = $collection->findOne(array("_id"=>12345));$data = $test->jsonSerialize();echo $data->_id;echo $data->filename;

Will output this:

12345myfile