sawrubh
sawrubh

Reputation: 321

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?

Upvotes: 15

Views: 19332

Answers (4)

Andre
Andre

Reputation: 2469

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 

Upvotes: 11

Saahithyan Vigneswaran
Saahithyan Vigneswaran

Reputation: 7143

I had the same problem and this is how I accessed the values inside. This works with find.

foreach ($result as $entry) {
   echo $entry['_id'], $entry['val1'], ['val2'];
}

Hope this helps someone.

Upvotes: -1

Marius.C
Marius.C

Reputation: 710

Another way would be:

json_encode( $bsonDoc->getArrayCopy() );

Upvotes: 8

pitchblack408
pitchblack408

Reputation: 2983

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
}

Upvotes: 16

Related Questions