我的示例代码:
<?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中:
查看第1次的页面时,这是正确的。
> 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被插入?谢谢。
是否打算为每个IP或每个URL的一个文档(包含一组IP)创建一个文档? –
我更喜欢每个ip的1个文件,因为可以跟踪每个IP点击数 – user1457750