How to get values from a PHP file querying MongoDB in jQuery's getJSON()? -


i learning mongodb , hoped because data stored in mongodb databases in format similar json able query mongodb directly jquery's getjson() method.

i learning seems need mongodb , driver access database application. going php driver time being.

i trying return value of content field:

mongodb document

{    "_id": objectid("34576347347"),    "content": "here content",    "field2": {      "subfield1": {        "0": "sf1v0",        "1": "sf1v1",        "2": "sf1v2"      },      "subfield2": "value 2"    },    "field2": "value 3"  } 

php

<?php   $dbhost = 'username:password@127.x.xx.x:27017/'; $dbname = 'dbname'; $m = new mongoclient("mongodb://$dbhost"); $db = $m->$dbname; $collection = $db->mycollection; $query = $collection->find(array("field2.subfield2" => "value 2"));  header("content-type: application/json"); echo json_encode($query);  ?> 

jquery

$.getjson("http://path/to/mongo.php", {cid: href, format: 'json'}, function(results){   $("#my_div").html(results[0].content); } 

i think need 'get' few things:

1) being returned php query:

$query = $collection->find(array("field2.subfield2" => "value 2")); 

i think mongodb terminology it returning cursor, php array, or json data or else?

2) correct 'call' make in getjson() code return required data?

at moment firebug showing me:

typeerror: results[0] undefined 

update

i changed getjson() code to:

$("#my_div").html(results.content); 

and don't error, following firebug:

response tab shows: {}

json tab shows: there no properties show object.

you want convert cursor returned find() function json_encode can use so:

$cursor = $collection->find(array("field2.subfield2" => "value 2")); echo json_encode(iterator_to_array($cursor, false)); 

this because query not run until iterate cursor. iterator_to_array exhaust cursor, documents, , put them array json_encode.

edit

specifying false second $use_keys argument iterator_to_array() ensure results indexed numerically (instead of _id field of each document).


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -