简体   繁体   English

如何在PHP中将MongoDB BSONDocument转换为有效的JSON?

[英]How to convert MongoDB BSONDocument to valid JSON in PHP?

I am using MongoDB with the PHP Library. 我正在使用MongoDB和PHP库。 I inserted a valid JSON document inside MongoDB using PHP. 我使用PHP在MongoDB中插入了一个有效的JSON文档。 I am now retrieving the document using findOne and am getting a MongoDB\\Model\\BSONDocument object as a result. 我现在正在使用findOne检索文档,结果得到一个MongoDB \\ Model \\ BSONDocument对象。 How do I get back my JSON document easily? 如何轻松取回我的JSON文档? Is there any inbuilt function or will I have to write logic to convert the BSONDocument to JSON? 是否有任何内置函数或我是否必须编写逻辑来将BSONDocument转换为JSON?

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. 我做了一些研究,看来当你创建一个MongoDB \\ Model \\ BSONDocument文档时,有一个bsonSerialize()方法。 This method will return a stdClass Object which is really the PHP Array Class. 此方法将返回一个stdClass对象,它实际上是PHP数组类。 According to documentation one can then convert from PHP to BSON and then to JSON. 根据文档,然后可以从PHP转换为BSON然后转换为JSON。

This is crazy looking, but it works. 这看起来很疯狂,但它确实有效。 Here is my example $accountResultDoc is of MongoDB\\Model\\BSONDocument type. 这是我的示例$ accountResultDoc是MongoDB \\ Model \\ BSONDocument类型。

$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
}

另一种方式是:

json_encode( $bsonDoc->getArrayCopy() );

The BSONDocument object has a jsonSerialize method. BSONDocument对象具有jsonSerialize方法。 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 

I had the same problem and this is how I accessed the values inside. 我有同样的问题,这就是我访问里面的值的方式。 This works with find . 这与find

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

Hope this helps someone. 希望这有助于某人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM