将带有映射和聚合的Mongodb shell查询转换为php
我编写了一个mongodb查询,很难将其转换为php代码:将带有映射和聚合的Mongodb shell查询转换为php,php,mongodb,mongodb-query,relational-database,aggregation-framework,Php,Mongodb,Mongodb Query,Relational Database,Aggregation Framework,我编写了一个mongodb查询,很难将其转换为php代码: var geoips = db.geoip.find().map(function(like){ return like.ip; }); var result = db.audit.aggregate([ { $match: { ip: { $nin: geoips } } }, { $group: { _id: "$ip", count: { $sum: 1 } }} ]);
var geoips = db.geoip.find().map(function(like){ return like.ip; });
var result = db.audit.aggregate([
{ $match: { ip: { $nin: geoips } } },
{ $group: {
_id: "$ip",
count: { $sum: 1 }
}}
]);
更新:
上面的查询相当于下面的关系数据库查询
Select ip,count(*)
from audit
where ip not in (select ip from geoip)
group by ip
因为我必须在mongodb版本3.0中进行此查询,所以我无法按照回答中的建议利用$lookup
下面的PHP代码实现了上述目标并按预期工作。它从geoip集合中获取不同的IP。它传递该结果并对审核集合进行聚合以获得所需的结果
$geoipcolln = $this->dbConn->selectCollection('geoip');
$geoips = $geoipcolln->distinct('ip');
$match = array('ip' => array('$nin' => $geoips));
$result = $this->collection->aggregate(
array(
'$match' => $match
),
array('$group' => array(
'_id' => '$ip',
'count' => array('$sum' => 1.0),
))
);
这可以使用操作符在一个聚合查询中完成,如下所示:
var result = db.audit.aggregate([
{
"$lookup": {
"from": "geoip",
"localField": "ip",
"foreignField": "ip",
"as": "geoips"
}
},
{ "$match": { "geoips.0": { "$exists": false } } },
{ "$group": {
"_id": "$ip",
"count": { "$sum": 1 }
}}
])
然后可以将其转换为PHP,如下所示:
<?php
$m = new MongoClient("localhost");
$c = $m->selectDB("yourDB")->selectCollection("audit");
$ops = array(
array(
"$lookup" => array(
"from" => "geoip",
"localField" => "ip",
"foreignField" => "ip",
"as" => "geoips"
)
),
array( "$match" => array( "geoips.0" => array( "$exists" => false ) ) ),
array( "$group" => array(
"_id" => "$ip",
"count" => array( "$sum" => 1 )
))
);
$results = $c->aggregate($ops);
var_dump($results);
?>
从性能角度看,这似乎是一个很好的替代方案。但是,我目前运行的是mongodb 3.0版本。看起来$lookup需要3.2版本。此时,我将无法升级。