我尝试使用更新在现有集合中添加一些值,但我只检索最后一个值:
举个例子:
当我尝试在MongoDB中向此文档添加一个具有不同值的数组时,如下所示:
$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)
);
}
我得到的结果是:
Array
(
[_id] => MongoId Object
(
)
[five] => Item5
[four] => Item4
[new] => 4
[one] => Item1
[six] => Item6
[three] => Item3
[two] => Item2
)
我想得到这样的东西:
Array
(
[_id] => MongoId Object
(
)
[five] => Item5
[four] => Item4
[new] => array(1,2,3,4)
[one] => Item1
[six] => Item6
[three] => Item3
[two] => Item2
)
请问我如何完成此操作的任何建议?谢谢!!!
这就是问题所在。YOu 覆盖脚本每次迭代中键new
的值。
您需要做的是以下内容
$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)
);