如何使用php驱动程序返回与给定条件匹配的文档计数


How return count of documents that match a given criteria using the php driver?

我收藏的文档如下所示:

{
    "state": "Wyoming",
    "high": {
        "fahrenheit": 115,
        "city": "Basin"
    },
    "low": {
        "fahrenheit": -63,
        "city": "Moran"
    }
}

显示高华氏温度大于或等于120且低华氏温度小于或等于-60的文档总数。

与shell一样,PHP驱动程序提供了.count方法,这正是您在这里所需要的,而且为了访问嵌入文档中的"fahrenheit"字段,您需要使用点表示法。

$collection->count(
    array(
        "high.fahrenheit" => array("$gte" => 120),
        "low.fahrenheit" => array("$lte" => -60)
    )
)

这相当于shell中的以下查询:

db.collection.count({ 
    "high.fahrenheit": { "$gte": 120 }, 
    "low.fahrenheit": { "$lte": -60 } 
})