簡體   English   中英

使用$ inc和$ addToSet進行MongoDB更新

[英]MongoDB upsert with $inc and $addToSet

我的示例代碼:

<?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? 謝謝。

如果我做對了,您粘貼的代碼每次都以這種方式執行嗎?
您獲得另一個ip條目的問題是'$addToSet' => array('visitors' => array('ip' => $ip))'$addToSet' => array('visitors' => array('ip' => $ip))因為您的數組不包含僅包含ip的字段,它將插入另一個(您的字段另外具有pageview屬性)。 您需要完全匹配。
不確定是否有解決此問題的指導原則,但我認為您應該使用像這樣的文檔結構:

{_id:ObjectId(.....),...,訪問者:{192.168.1.1:{pageview:1}}。 因此,您只需運行此更新命令(使用mongoshell語法),即可將兩個更新進一步合並為一個:):

db.c.update({"url":"/test.php","date":"today"},{$inc : {"192.168.1.1" : {pageview:1}, pageview: 1}},true)來更新您的文檔。 無論如何,您都需要用其他字符替換這些點,否則將無法正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM