简体   繁体   中英

MongoDB -PHP data update

For save data from form to MongoDB database i'm using this code.

if (isset($_POST))
{   
    $m = new MongoClient();   
    $db = $m->abst;
    $collection = $db->users;
    print_r($_POST);    
    if($collection->find(array('user_id' => $pid)))
    {
        $collection->update(array('user_id'=>$pid),$_POST);
    }
    else
    { 
        $document = array_merge(array('user_id'=>$pid),$_POST);
        $collection->insert($document);   
    }  
}

How can check user id exist in collection? and if user id exist in collection, data will update. Otherwise new entry saved to collection. where is the mistake?

Try this - maybe it will work for you.

In MongoDB if a record does not exist for given query and if upsert is true then mongodb adds the record as a new record.

$query['user_id'] = $pid;
$object['$set'] = $_POST;
$options = array('w' => true, 'upsert' => true);
$collection->update($query, $object, $options);

try this

if($collection->find(array('user_id' => $pid))->count() == 1)
    {
        $collection->update(array('user_id'=>$pid),$_POST);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM