2

I update an existing document with the code below. Its working fine.

foreach($jArray as $value){ 
!!some code!!
    try {
        $collection->update(array("tablename"=>$tablename),array('$push' => array("inventar" => $new_data)));
        echo json_encode($collection);
    }
    catch ( MongoConnectionException $e ) {
        echo '<p>Update failed</p>';
        exit();
    }           
}

JSON response:

{"w":1,"wtimeout":10000}{"w":1,"wtimeout":10000}

(2 values are tried to update)

Even if no tablename matched, means no update happend, the result is w = 1. Why? No update happend and w is 1/true?

Piet
  • 395
  • 2
  • 7
  • 17
  • This jumps out `'$push'`. Did you mean to use `"` (double quotes) there? – ficuscr Jun 15 '15 at 19:17
  • it is working with `'$push'` with double quotes: `Uncaught exception 'MongoException' with message 'zero-length keys are not allowed, did you use $ with double quotes?'` – Piet Jun 15 '15 at 19:23
  • Not clear on your last comment. Are you saying that fixed it and now the error message you got makes sense? You understand the distinction between `'$foo'` and `"$foo"` yes? Assuming that's the case. More here... http://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php – ficuscr Jun 15 '15 at 19:25
  • I didnt understand ficuscr comment. my code is working, but the return value of the push is always w : 1 , even when no collection exists in the database and no value is written. You ever worked with php/mongodb? my code is right there – Piet Jun 15 '15 at 19:27
  • Oh. Wow never mind. MongoDB does use `$` I thought you were trying to use the value of that variable... `{ $push: { field: value1 } }` Coming from PHP that's a bit confusing. I don't use Mongo much... Have like 20 of their coffee mugs though :) – ficuscr Jun 15 '15 at 19:33

1 Answers1

0

There seems to be a little confusion here. The JSON response you are looking at is not the actual return value from the update operation. What you did was JSONifying the collection itself, which has the integer attributes w and wtimeout (see source code here). Those attributes are in no way related to the result of the update operation itself.

So, the right way to go seems to be changing the lines inside the scope of your try statement to:

$result = $collection->update(array("tablename"=>$tablename),array('$push' => array("inventar" => $new_data)));
echo json_encode($result);

For more information about what is returned from the update method, refer to these docs.

lucasnadalutti
  • 5,818
  • 1
  • 28
  • 48