I’m querying a MongoDB database with PHP and what happens is the document response is returned as an array of nested arrays.
Here’s a var_dump of the response:
Array
(
[_id] => MongoId Object
(
[$id] => 4ea06851fe90d0662900000a
)
[name] => Jason A,
[address] => Array
(
[0] => Array
(
[line1] => 123 Main St
[city] => Chicago
[zip] => 60611
[longitude] => -81.59
[county] => Cook
[state] => IL
[latitude] => 28.32
)
)
[kids] => Array
(
[0] => Array
(
[name] => Child One
[age] => 12
)
[1] => Array
(
[name] => Child Two
[age] => 4
)
)
)
When I query MongoDB via the command console, I can see that the document is stored with the object intact, curly braces and all:
{
"_id" : ObjectId("4ea06851fe90d0662900000a"),
"name" : "Jason A",
"address" : {
"line1":"123 Main St"
"city" : "Chicago",
"zip" : "60611",
"country" : "US",
"longitude" : -81.59,
"state" : "IL",
"latitude" : 28.32
},
"kids" : [
{
"name" : "Child One",
"age" : 12
},
{
"name" : "Child Two",
"age" : "4"
}
]
}
How can I query MongoDB via PHP and retain the object intact?
If I understand what’s happening correctly, you’re seeing “intact objects” in the MongoDB databases, “curly braces and all.” These records are actually not much more than standard associative arrays, stored in BSON.
When you insert a PHP object into a MongoDB database, the MongoDB actually converts your PHP object into a sort of associative array, which it then stores as BSON. This is why when you query for your object back, you only receive an “array of arrays.”
Try calling var_dump on the array you get, and see if it contains the data you expected. If not, most likely MongoDB could not properly store the data in your object in BSON.