[英]How do I return result with a specific value first in mongodb && php
[英]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())) {
$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.