0

我正在使用 PHP 向 MongoDB 添加文档。

我已经使用 RockMongo 验证了文件已成功添加。

但是,当我运行 find() 命令时,它返回一个空数组

$insert = $collection->insert($document);
$cursor = $collection->find();

insert 会插入文档,但是 find() 返回“MongoCursor Object()”

插入后是否需要运行命令才能找到该项目?

4

1 回答 1

2

从文档中获取: find 返回指向资源的指针,您必须遍历结果才能实际查看结果。(就像 mysql(i)) http://php.net/manual/en/mongocollection.find.php

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'produce');

// search for fruits
$fruitQuery = array('Type' => 'Fruit');

$cursor = $collection->find($fruitQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

// search for produce that is sweet. Taste is a child of Details. 
$sweetQuery = array('Details.Taste' => 'Sweet');
echo "Sweet\n";
$cursor = $collection->find($sweetQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

?>

因此,如果您对结果进行 foreach,它会正常工作!

于 2013-02-11T09:03:46.140 回答