我的示例代碼:
<?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