未定义的索引:mongodb foreach php

时间:2018-05-31 20:12:55

标签: php mongodb

我正在使用php测试mongodb,我遇到了一个我不知道如何解决的问题,这是我目前正在使用的代码。

<?php

require ($_SERVER['DOCUMENT_ROOT'] . '/grafic/mongodb_php/vendor/autoload.php'); 

$client = new MongoDB\Client;
$snrdb = $client->snrdb;
$nodos_live = $snrdb->nodos_live;

$filter  = [];
$options = ['sort' => ['_id' => 1], 'limit' => 1];

$show = $nodos_live->find($filter, $options);

foreach ($show as $collection) {
    $snr_1= $collection["n1_snr_1"];
    $snr_2= $collection["n1_snr_2"];
}

echo $snr_1 ." ";
echo $snr_2;

?>

这给了我

28.9 28.3

现在,如果我将id和集合名称更改为2,并将n2_snr_ *更改为如此。

<?php

require ($_SERVER['DOCUMENT_ROOT'] . '/grafic/mongodb_php/vendor/autoload.php'); 

$client = new MongoDB\Client;
$snrdb = $client->snrdb;
$nodos_live = $snrdb->nodos_live;

$filter  = [];
$options = ['sort' => ['_id' => 2], 'limit' => 1];

$show = $nodos_live->find($filter, $options);

foreach ($show as $collection) {
    $snr_1= $collection["n2_snr_1"];
    $snr_2= $collection["n2_snr_2"];
}

echo $snr_1 ." ";
echo $snr_2;

?>

这给了我这个错误信息:

  

致命错误:未捕获的MongoDB \ Driver \ Exception \ ConnectionException:C:\ xampp \ htdocs \ grafic \ mongodb_php \ vendor \ mongodb \ mongodb \ src \ Operation \ Find.php中的错误排序规范:287       堆栈跟踪:       #0 C:\ xampp \ htdocs \ grafic \ mongodb_php \ vendor \ mongodb \ mongodb \ src \ Operation \ Find.php(287):MongoDB \ Driver \ Server-&gt; executeQuery(&#39; snrdb.nodos_liv ... &#39;,对象(MongoDB \ Driver \ Query),数组)       #1 C:\ xampp \ htdocs \ grafic \ mongodb_php \ vendor \ mongodb \ mongodb \ src \ Collection.php(531):MongoDB \ Operation \ Find-&gt; execute(Object(MongoDB \ Driver \ Server))       #2 C:\ xampp \ htdocs \ grafic \ test \ test.php(23):MongoDB \ Collection-&gt; find(Array,Array)       #3 {main}         抛出 C:\ xampp \ htdocs \ grafic \ mongodb_php \ vendor \ mongodb \ mongodb \ src \ Operation \ Find.php 287

我无法理解为什么我会得到这个错误的消息,任何可以帮助我的人?

如果像这样做转储

<?php 

require ($_SERVER['DOCUMENT_ROOT'] . '/grafic/mongodb_php/vendor/autoload.php'); 

$client = new MongoDB\Client;
$snrdb = $client->snrdb;
$nodos_live = $snrdb->nodos_live;

$show = $nodos_live->findOne(
    ['_id' => '1']
);

var_dump($show)

?>

我知道这是一个id为1的文件

object(MongoDB\Model\BSONDocument)#19 (1) {
  ["storage":"ArrayObject":private]=>
  array(5) {
    ["_id"]=>
    string(1) "1"
    ["n1_snr_1"]=>
    float(28.9)
    ["n1_snr_2"]=>
    float(28.3)
    ["n1_snr_3"]=>
    string(1) "0"
    ["time_stamp"]=>
    string(19) "2018-05-31 21:44:22"
  }
}

同样的,我做了_id =&gt;的转储。 2它表明它也存在。

object(MongoDB\Model\BSONDocument)#19 (1) {
  ["storage":"ArrayObject":private]=>
  array(5) {
    ["_id"]=>
    string(1) "2"
    ["n2_snr_1"]=>
    float(31.7)
    ["n2_snr_2"]=>
    float(35.7)
    ["n2_snr_3"]=>
    string(1) "0"
    ["time_stamp"]=>
    string(19) "2018-05-31 21:44:22"
  }
}

1 个答案:

答案 0 :(得分:2)

sort只能将两个值1用于升序,-1用于降序。如果要使用_id=2查询文档,则必须在查询中指定该文档,而不是在排序条件中指定。