How to convert MongoDB BSONDocument to valid JSON in PHP?
Asked Answered
E

4

15

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?

Epi answered 18/2, 2016 at 4:25 Comment(6)
There seems to be a general confusion with this driver change. You appear to be using the mongodb pecl extension directly, when the intent is to use the higher level abstraction library here. That library will just yield plain objects, which will serialize to JSON simply. So the lower level driver you are using is intended to be used by other libraries providing abstraction. The "userland" library should always be something abstracting from that source.Plesiosaur
findOne is a function from that higher level abstraction library, isn't it? If not, please let me know which function should I use to query documents by their ObjectId. BTW I'm using insertOne to insert the document. Not sure if using that to insert is right as well.Epi
It's a method in all higher and lower libraries. Which do you actually have installed? You just got links for reference. Please use them.Plesiosaur
So I have followed the installation steps given on the higher level library page but am not sure how to check if I'm somehow using the lower level driver even though I don't intend to. Here's the code I'm using <?php require 'vendor/autoload.php'; $client = new MongoDB\Client; $coll = $client->test->menu; $doc = $coll->findOne(['_id'=> new MongoDB\BSON\ObjectId('56c43f5732a99d04727588d5')]); var_dump(json_encode($doc)); ?>Epi
So according to the documentation of the findOne function from the higher level library as well, the returned value is a MongoDB\Model\BSONDocument instead of a plain object as you said.Epi
One difference though between the function given in the documentation and my code is that the documentation directly uses the ObjectId as a string however when I try to do so it doesn't work, so I have to convert the ObjectId in my case (56c43f5732a99d04727588d5) to a MongoDB\BSON\ObjectId and then pass it to findOne.Epi
P
16

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
}
Pinky answered 11/3, 2016 at 5:45 Comment(0)
W
11

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 
Whooper answered 20/6, 2017 at 10:51 Comment(0)
M
7

Another way would be:

json_encode( $bsonDoc->getArrayCopy() );

Meshuga answered 21/11, 2016 at 18:2 Comment(0)
T
-1

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.

Thrombokinase answered 28/11, 2016 at 18:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.