Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php mongodb - can't get upsert working

Tags:

php

mongodb

I'm running the following code and it works great, if no record exists it creates a new one. What I'm trying to do is modify this query so that the 'v' field also increases +1 but I'm not having any luck. Can someone help me out?

            $result = $collection->update(
                array('k'=>md5(SITE_ID.'-'.$_SERVER['HTTP_X_FORWARDED_FOR'])),
                array('$set'=>
                    array(
                        'k'=>md5(SITE_ID.'-'.$_SERVER['HTTP_X_FORWARDED_FOR']),                                                                   'st'=>SITE_ID, 
                        'ur'=>$_GET['u'],                                                
                        'ts'=>time(),
                        'dt'=>date('Ymd'), 
                        'ur'=>$_GET['p'],
                        'v'=>1
                    ),
                    array(
                        '$inc' => array('v' => 1)
                    ),
                ),
                array('upsert'=>true)
            );
like image 481
Joe Avatar asked Nov 08 '12 21:11

Joe


1 Answers

Put both the $set and the $inc in a single object:

$result = $collection->update(
    array('k'=>md5(SITE_ID.'-'.$_SERVER['HTTP_X_FORWARDED_FOR'])),
    array(
        '$set'=> array(
                'k'=>md5(SITE_ID.'-'.$_SERVER['HTTP_X_FORWARDED_FOR']),                                                                   'st'=>SITE_ID, 
                'ur'=>$_GET['u'],                                                
                'ts'=>time(),
                'dt'=>date('Ymd'), 
                'ur'=>$_GET['p']
            ),
        '$inc' => array('v' => 1)
    ),
    array('upsert'=>true)
);
like image 103
JohnnyHK Avatar answered Sep 22 '22 02:09

JohnnyHK