繁体   English   中英

如何在 PHP 中检查 MongoDB 结果是否为空

[英]How do I check if MongoDB result is empty in PHP

$cursor = $collection->find(/*...*/);

if (empty($cursor)) {
    echo "List is empty!";
} else {
    foreach ($cursor as $products) {
        // do something
    }
}

不幸的是, empty不适用于 MongoDB 结果。

我不使用 MongoDB,所以我根据评论进行了更新。 使用$collection->count()

检查它是否评估为falsey值:

if(!$collection->count()) {

或检查0

if($collection->count() == 0) {

或者你可以检查empty

if(empty($collection->count())) {

我们可以使用游标的isDead()方法

if (!$products->isDead()) {
    // there are some results
}

请参阅有关PHP 驱动程序文档的相关 文档

$cursor是一个对象,所以它总是评估为真

并且 mongodb 的 PHP 驱动程序中没有$cursor->count()

请注意,Mongodb 的 PHP 驱动程序与其他驱动程序不同。

试试这个:

if ($collection->count(...)) {
   // note you must pass the query to the count function
   $cursor = $collection->find(...);
   foreach ($cursor as $products) {

   }
} else {
    echo "List is empty!";
}

或者:

$cursor = $collection->find(...);

if (!count($cursor->toarray())) { // convert to array and count it 

    echo "List is empty!";
} else {

    foreach ($cursor as $products) {
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM