【发布时间】:2015-02-26 06:56:32
【问题描述】:
有没有办法在 Doctrine 中使用 MongoDB 执行原始查询(就像使用 MySQL 一样)? 我正在尝试这样做:
db.report.aggregate([{"$group" : {_id:"$content", count:{$sum:1}}}])
它似乎也不是 Doctrine 中的原生聚合函数,是吗?
【问题讨论】:
有没有办法在 Doctrine 中使用 MongoDB 执行原始查询(就像使用 MySQL 一样)? 我正在尝试这样做:
db.report.aggregate([{"$group" : {_id:"$content", count:{$sum:1}}}])
它似乎也不是 Doctrine 中的原生聚合函数,是吗?
【问题讨论】:
以下对我有用
$dbName = $this->container->getParameter('mongo_db_name');
$connection = $this->container->get('doctrine_mongodb')->getConnection();
$mongo = $connection->getMongo();
$db = $mongo->selectDB($dbName);
$results = $db ->command([
'aggregate' => 'report',
'pipeline' => [
['$group' => ['_id' => '$content', 'count' => ['$sum' => 1]]]
]
]);
return $results;
不确定原生 Doctrine 函数,但在聚合的情况下,我更喜欢 RAW JSON 输出,因为它主要用于渲染一些图表。
【讨论】:
在 Doctrine ODM 2.0 中,底层连接由mongodb/mongodb package 处理,而不是由doctrine/mongodb 处理。因此,您可以通过学说 ManagerRegistry::getConnection(), then use the command function using the mongodb library:
获得连接use Doctrine\Bundle\MongoDBBundle\ManagerRegistry;
class Test {
function execute(ManagerRegistry $mr) {
$database= $mr->getConnection()->db_name;
$cursor = $database->command([
'geoNear' => 'restos',
'near' => [
'type' => 'Point',
'coordinates' => [-74.0, 40.0],
],
'spherical' => 'true',
'num' => 3,
]);
$results = $cursor->toArray()[0];
var_dump($results);
}
}
【讨论】:
就我而言,我使用聚合
$db = $mongo->selectDB('ostrov_sync');
$dbTable = $mongo->selectCollection($db, 'sync_task');
$results = $dbTable->aggregate([
[
'$match' => [
'payloadHash' => [
'$eq' => '0000cfdc-c8cf-11e9-9485-000c29d1ed7a',
],
],
]
]);
dump(results);
【讨论】: