Decoding JSON using PHP from Mongo

泪湿孤枕 提交于 2019-12-03 21:37:18

MongoDB does not store the data as JSON.

The document you pasted seems to be copy&paste from the shell. This is not JSON format either. This format is called Extended JSON - and is how the MongoDB shell represents the data in javascript. Most examples on the MongoDB website also use this format as it is simple and easy. So rather then have dozens of different output format (for each language driver), the MongoDB official documentations use the shell for demonstrating functionality and output.

The actual underlaying format is called Binary JSON (BSON). You will never see this format and you will never interact with it.

When you interact with MongoDB in PHP all you have to know is that you save a PHP array. The data returned from MongoDB is also a PHP array. The underlaying disk format is not relevant.

You never have to call json_encode() or json_decode().

The $collection->find($query) method returns a object called MongoCursor. You should iterate over this object to get the results, which will be a PHP array.

foreach($collection->find($query) as $result) {
    var_dump($result);
}

This code example will var_dump() one result at a time. This result is called a "MongoDB Document" and is similar to "MySQL row". Just like with MySQL, you don't have to know what the underlaying protocol is, or what the underlaying disk format is - that has no affect on you.

I strongly suggest you read the MongoDB PHP Driver tutorial: http://us2.php.net/manual/en/mongo.tutorial.php

This should explain the concept a littlebit better, along with how the driver works :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!