我写了一个 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 }
}}
]);
更新:
上面的查询等价于下面的关系数据库查询
Select ip,count(*)
from audit
where ip not in (select ip from geoip)
group by ip
由于我必须在 mongodb 3.0 版中进行此查询,因此我无法按照答案中的建议利用 $lookup。
下面的 PHP 代码实现了上述目标并按预期工作。它从 geoip 集合中获取不同的 ips。它传递该结果并对审计集合进行聚合以获得所需的结果。
$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),
))
);
最佳答案
这可以在一个聚合查询中使用 $lookup
完成 运算符如下:
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);
?>
关于php - 使用映射和聚合将 Mongodb shell 查询转换为 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40299593/