douhui3305 2017-02-17 11:08
浏览 69
已采纳

PHP MongoDB在更新时取消设置字段

My problem is that when I submit a form and record it to MongoDB.

I am able to add new fields to a document using update, I can change their values and keys, but I'm not able to remove / unset them.

I'm pretty new to Mongo. I normally work with the stack: MySQL+PHP+Bootstrap, but for production reasons we need to add Mongo to the equation.

Here is how a document of my collection looks:

{
   "_id": ObjectId("58a44a61e09075e805d63af1"),
   "en": "Cat",
   "de": "Katze",
   "es": "Gato",
}

During Submit, I can edit it this way:

{
   "_id": ObjectId("58a44a61e09075e805d63af1"),
   "en": "Cat",
   "de": "Katze",
   "fr": "Chat",
}

Or this way:

{
   "_id": ObjectId("58a44a61e09075e805d63af1"),
   "en": "Cat",
   "de": "Katze",
   "es": "Gato",
   "fr": "Chat",
}

But I'm unable to do this:

{
   "_id": ObjectId("58a44a61e09075e805d63af1"),
   "en": "Cat",
   "de": "Katze"
}

Here is my form:

<form role="form" action="" method="post">
   <table>
     <?php
       foreach ($glossary as $term) {
         foreach (array_slice($keys,1) as $key => $value) {
            echo "<tr id='language" . $key . "' class='languages'>";
               echo "<td>";
                  echo "<select class='form-control' name='lang" . $key . "'>";
                    echo "<option value='' selected></option>";
                    // Options not shown for simplicity.
                  echo "</select>";
               echo "</td>";
               echo "<td>";
                  echo "<input class='form-control' value='$term[$value]' name='langInput" . $key . "'>";
               echo "</td>";
            echo "</tr>";
        }
      }
    }
    ?>
   </table>

 <input type="submit" name="submit" class="btn btn-primary" value="Save Changes">

On submit I do:

   $termArray = array();

   // Get submitted form vars
   for ($i = 0; $i <= $loop; $i++ ) {
       $langCode = cleanFormFld($_POST["lang".$i]);
       $termArray[$langCode] = cleanFormFld($_POST["langInput".$i]);
   }

   try {          
       $connection = new Mongo("mongodb://$dbhost");
       $db = $connection->$dbname;

       $db->terms->update(array('_id' => new MongoId($id)), array('$set' => $termArray));
   }
   catch(PDOException $e) {
       echo "Error: " . $e->getMessage();
   }

Every langX and langInputX are created dinamicaly in jQuery.

  • 写回答

2条回答 默认 最新

  • doushaiyu5065 2017-02-18 17:16
    关注
    $db->terms->update(array('_id' => new MongoId($id)), array('$set' => $termArray));
    

    Using $set modifier doesn't allow you to unset fields, it aims to update fields you specify. If you want to replace whole document (effectively having only the data you're passing to the function) you should write

    $db->terms->update(array('_id' => new MongoId($id)), $termArray);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?