Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I try to add some values in existing Collection using Update but I retrieve just just the last value:

An example:

When I try to add to this document in MongoDB an array with different values like this:

   $test=
array("one"=>"Item1","two"=>"Item2","three"=>"Item3","four"=>"Item4",
  "five"=>"Item5","six"=>"Item6");

  $collectionMeasurements->insert($test);
  for($i=0;$i<5;$i++){
   $collectionMeasurements->update(
         array("one" => "Item1"),
         array('$set' => array('new' => $i)),
         array("multiple" => true)
  );

  } 

I get as results:

Array
 (
 [_id] => MongoId Object
    (
    )

[five] => Item5
[four] => Item4
[new] => 4
[one] => Item1
[six] => Item6
[three] => Item3
[two] => Item2
 )

I would like to get something like that:

Array
  (
   [_id] => MongoId Object
    (
    )

[five] => Item5
[four] => Item4
[new] => array(1,2,3,4)
[one] => Item1
[six] => Item6
[three] => Item3
[two] => Item2
 )

Any suggestion of how I can accomplish this please? Thanks!!!

share|improve this question
 
post your mongo output as a normal json, not a php print_r() –  Salvador Dali Nov 11 at 8:53

1 Answer

up vote 0 down vote accepted

Here is the problem. YOu overwrite the value for a key new in each iteration of your script.

What you have to do is the following

$arr = array()
for($i=0;$i<5;$i++){
   arr[$i] = $i; // or initialize array in a normal way
}

$collectionMeasurements->update(
   array("one" => "Item1"),
   array('$set' => array('new' => $arr)),
   array("multiple" => true)
);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.