有没有办法在Doctrine中使用MongoDB执行原始查询(就像使用MySQL一样)? 我试图这样做:
db.report.aggregate([{"$group" : {_id:"$content", count:{$sum:1}}}])
它似乎也不是Doctrine中的本机聚合函数,是吗?
答案 0 :(得分:2)
以下为我做了诀窍
$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输出,因为它主要用于渲染一些图表。
答案 1 :(得分:0)
在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);
}
}
答案 2 :(得分:0)
就我而言,我使用汇总
$db = $mongo->selectDB('ostrov_sync');
$dbTable = $mongo->selectCollection($db, 'sync_task');
$results = $dbTable->aggregate([
[
'$match' => [
'payloadHash' => [
'$eq' => '0000cfdc-c8cf-11e9-9485-000c29d1ed7a',
],
],
]
]);
dump(results);