Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert MongoDB BSONDocument to valid JSON in PHP?

I am using MongoDB with the PHP Library. I inserted a valid JSON document inside MongoDB using PHP. I am now retrieving the document using findOne and am getting a MongoDB\Model\BSONDocument object as a result. How do I get back my JSON document easily? Is there any inbuilt function or will I have to write logic to convert the BSONDocument to JSON?

like image 880
sawrubh Avatar asked Feb 18 '16 04:02

sawrubh


2 Answers

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
}
like image 175
pitchblack408 Avatar answered Sep 22 '22 10:09

pitchblack408


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:

12345
myfile 
like image 23
Andre Avatar answered Sep 22 '22 10:09

Andre