我的示例代码:
<?php
$m = new Mongo();
$db = $m->selectDB('metrics');
$collection = new MongoCollection($db, 'counter');
$url = $_SERVER['REQUEST_URI'];
$ip = '192.168.1.1';
$user = 'testuser';
$today = date('Y-m-d');
//upsert 1st
$filter = array('url' => $url, 'date' => $today);
$data2 = array(
'$inc' => array("pageview" => 1),
'$addToSet' => array('visitors' => array('ip' => $ip))
);
$options = array("upsert" => true);
$collection->update( $filter, $data2, $options );
//update the pageview for unique ip after that
$filter1 = array( 'url' => $url, 'date' => $today, 'visitors' => array( '$elemMatch' => array( 'ip' => $ip ) ) );
$update1 = array( '$inc' => array( 'visitors.$.pageview' => 1 ) );
$collection->update( $filter1, $update1 );
?>
MongoDB中的数据:
第一次查看页面时这是正确的。
> db.counter.find();
{ "_id" : ObjectId("4fdaaf1176c5c9fca444ffd3"), "date" : "2012-06-14", "pageview" : 1, "url" : "/mongo/test.php", "visitors" : [ { "ip" : "192.168.1.1", "pageview" : 1 } ] }
刷新页面后,添加奇怪的数据:
> db.counter.find();
{ "_id" : ObjectId("4fdaaf1176c5c9fca444ffd3"), "date" : "2012-06-14", "pageview" : 2, "url" : "/mongo/test.php", "visitors" : [ { "ip" : "192.168.1.1", "pageview" : 2 }, { "ip" : "192.168.1.1" } ] }
我将如何更正查询并防止插入额外的 IP?谢谢。