title: MongoDB upsert with $inc and $addToSet
body: <p>My sample code:</p>
  
  <pre><code>&lt;?php
  $m = new Mongo();
  
  $db = $m-&gt;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' =&gt; $url, 'date' =&gt; $today);
  $data2 = array(
                  '$inc' =&gt; array("pageview" =&gt; 1),
                  '$addToSet' =&gt; array('visitors' =&gt; array('ip' =&gt; $ip))
  );
  $options = array("upsert" =&gt; true);
  $collection-&gt;update( $filter, $data2, $options );
  
  
  //update the pageview for unique ip after that
  $filter1 = array( 'url' =&gt; $url, 'date' =&gt; $today, 'visitors' =&gt; array( '$elemMatch' =&gt; array( 'ip' =&gt; $ip ) ) );
  $update1 = array( '$inc' =&gt; array( 'visitors.$.pageview' =&gt; 1 ) );
  $collection-&gt;update( $filter1, $update1 );
  
  ?&gt;
  </code></pre>
  
  <p>Data in mongodb:</p>
  
  <p>This is correct when view the page for 1st time.</p>
  
  <pre><code>&gt; db.counter.find();
  { "_id" : ObjectId("4fdaaf1176c5c9fca444ffd3"), "date" : "2012-06-14", "pageview" : 1, "url" : "/mongo/test.php", "visitors" : [ { "ip" : "192.168.1.1", "pageview" : 1 } ] }
  </code></pre>
  
  <p>After refresh the page, adding weird data:</p>
  
  <pre><code>&gt; 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" } ] }
  </code></pre>
  
  <p>How would I correct query and prevent the extra IP from being inserted? Thanks.</p>