在PHP中如何检索mongoDB文档的文档内容


In PHP how to retrieve document content of a mongoDB Document?

我有以下脚本:

<?php
   // connect to mongodb
   $m = new MongoClient();
   // select a database
   $db = $m->myDB;
   $collection = $db->users;
   $cursor = $collection->find();
   //echo $cursor["Login"];
?>

我想从集合"用户"中显示"登录"的值,但我尝试过(echo $cursor["Login"]不起作用),有什么想法吗?

PS:我不想使用 foreach 语句

您正在尝试无条件地检索记录。因此,很明显,您的集合中存在的任何数量的记录users都将在此处检索。现在,由于您正在使用find()函数,因此无法通过echo直接获取值,因为它是对象(记录)的集合。

在这里,您可以使用foreach循环来迭代并从您现在不想要的每条记录中获取登录值,或者您可以使用findOne() 与内部具有条件的数组一起使用,以关联方式检索特定记录。

注意:您不能直接回显$cursor

说明findOne()

格式: $cursor = $collection->findOne(array('key' => 'value'));

阵列内可以有多个条件。

$cursor = $collection->findOne(array('login' => 'someemail@example.com'));

$cursor = $collection->findOne(array('login' => 'someemail@example.com','password' => 'some_password'));

请注意,findOne 可以为您提供与数组中提到的条件匹配的单个记录。

尝试print_r($cursor)看看会发生什么,可能$cursor不是数组