Question

my database structure

{
"Author_Name" : "mukund",
"Quote_Details" : [
    {
        "Quote_Text" : "Lost in the woods",
        "Quote_Catagory" : "Something",
        "Quote_Time" : "systime",
        "Occassion" : "some time",
        "Said_TO" : "somebody"
    },
    {
        "Quote_Text" : "Miles to go before i sleep",
        "Quote_Catagory" : "Nothing",
        "Quote_Time" : "besttime",
        "Occassion" : "i dont know",
        "Said_TO" : "Nobody"
    }
],
"_id" : ObjectId("535f6dc8b8082fd3f80dea0f")
}

My php code

$query = $collection->find(array("Quote_Details.Quote_Text" => new MongoRegex("/^$q/i"),"Author_Name" => "$author"));

$json2 = array();
   foreach($query as $result) 
        {  
            //echo $result['Quote']."\n" ;  
             $json2[]= array('val'=>$result["Author_Name"],
                'value'=>$result["Quote_Details.Quote_Text"]);
        }
        echo json_encode($json2);

i think it is working, coz when i am getting a value as null for only 'value' in text box when i input correct values. i am getting correct author names when provide q as "Lost in the woods" and author_name as "mukund", but in the place of 'value' it is shown as null

one more thing to note is that if i put any other value for q, as needed not output is obtained

the console output is

[{"val":"mukund","value":null}]

please tell me what i am doing wrong here

Was it helpful?

Solution

So the problem with your code is you are still trying to use the JSON notation for accessing the inner document when you actually need to be using the PHP notation. Since your PHP notation doesn't match anything you get the null result.

But really, this is not what you want to do as you are post processing the results in code. You could have done this server side very easily:

$result = $collection->aggregate(array(
  array(
    '$match' => array(
      'Quote_Details.Quote_Text' => MongoRegex("/^$q/i"),
      'Author_Name' => "$author"
    )
  ),
  array(
    '$unwind' => '$Quote_Details'
  ),
  array(
    '$project' => array(
      '_id' => 0,
      'val' => '$Author_Name',
      'value' => '$Quote_Details.Quote_Text'
    )
  )
));

echo json_encode( $result['result'], JSON_PRETTY_PRINT ) . "\n";

So now, as shown, you don't need to iterate the results anymore as you can just encode on the spot and you have re-shaped to exactly what you want in the result.

OTHER TIPS

As per my understanding, your collection is multidimensional (documents and subdocuments). So, you may get the "value" in result with below code :

instead of using :

$result["Quote_Details.Quote_Text"] 

In the foreach loop

use this instead :

$result["Quote_Details"]["Quote_Text"]

Above code gives you output as :

[{"val":"mukund","value":"Lost in the woods"}]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top