简体   繁体   中英

MongoDB Upsert not working in PHP

I am trying to run an update on my documents, I'm using upsert true but its still overwriting?

$col = "A" . $user->agencyID;
$db = $m->rules;
$collection = $db->$col;

$validValue = $_POST['validValue'];
$id = $_POST['ruleID'];

$document = array(
    'tags' => array(
                $validValue
              )
  );


$collection->update(
    array(
      '_id' => new MongoId($id)
      ),
    array('$set' => $document),
    array('upsert'=>true)
);

$validValue is like - Foo Bar

The first value goes in fine but when I try adding a different value it overwrites the first one?

设法找出问题,我需要$ addToSet ,还需要从我的$validValue获取array()

Actually, use $addToSet which will not push a value into the array if it already exists. This code is untested, please change to fit your needs.

$col = "A" . $user->agencyID;
$db = $m->rules;
$collection = $db->$col;

$validValue = $_POST['validValue'];
$id = $_POST['ruleID'];

$document = array(
    'tags' => array(
            $validValue
    )
);


$collection->update(
    array(
      '_id' => new MongoId($id)
    ),
    array('$addToSet' => array('tags' => $document))
);

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