user3324731 user3324731 - 9 months ago 44
PHP Question

Result set(Sub Documents) for a mongodb query in php

I am trying to get the result set output for a query. I was able to write the query and am getting the required result using var_dump.

$comment = array(
"Name" => array( 'FirstName' => $n1, 'LastName' => $n2 )
$cursor= $c_users->find( $comment );
$result = $cursor->getNext();
echo var_dump( $result );

But I am failing when i want to get output for a sub document.
In case of a normal document the below code works:

echo $result['variable'];

But consider a case where there is a document structure given below:

"Name" => array( 'FirstName' => $n1, 'LastName' => $n2 )

Could anyone help me with the syntax to output the first name. I was trying with below code
but did not succeed.

echo $result['variable.FirstName']

So the question is how to access embedded document of mongodb using PHP?

Thanks and Regards,


In order to access embedded document key (property) you need to treat embedded document like an array in PHP dot notation won't work in PHP for MongoDB so you should try:

echo $result['Name']['FirstName'];

Accessing embedded document with dot notation will work in mongoshell not in PHP driver.