我正在学习MongoDB,希望因为存储在MongoDB数据库中的数据格式与JSON非常相似,所以我可以直接从jQuery的getJSON()
方法查询MongoDB。
然而,我了解到,似乎需要MongoDB和driver
才能从应用程序访问数据库。因此,我暂时使用PHP驱动程序。
我正在尝试返回content
字段的value
:
MongoDB文档
{
"_id": ObjectId("34576347347"),
"content": "here is some 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);
}
我想我需要"得到"一些东西:
PHP查询返回的内容:
$query = $collection->find(array("field2.subfield2" => "value 2"));
我认为MongoDB的术语是返回
cursor
,但这是一个PHP数组,还是JSON数据或其他什么?在
getJSON()
代码中进行什么正确的"调用"以返回所需的数据?目前Firebug正在向我展示:
TypeError: results[0] is undefined
更新
我将getJSON()
代码更改为:
$("#my_div").html(results.content);
现在我没有得到错误,但以下来自Firebug:
响应选项卡显示:{}
JSON选项卡显示:此对象没有可显示的属性。
您想将find()
函数返回的光标转换为json_encode实际可以使用的东西,如下所示:
$cursor = $collection->find(array("field2.subfield2" => "value 2"));
echo json_encode(iterator_to_array($cursor, false));
这是因为在迭代游标之前,查询不会运行。Iterator_to_array基本上会耗尽光标,获取所有文档,并将它们放入json_encode的数组中。
编辑
将false
指定为iterator_to_array()
的第二个$use_keys
参数将确保结果以数字形式编制索引(而不是按每个文档的_id
字段编制索引)。