Background: Using CodeIgniter with this MongoDB library.
This is my first go-round with mongodb and I’m enjoying it thus far. It’s taken a while for me to separate myself from the sql way of thinking, but it is a perfect fit for my current project.
I’m trying to push an array into a document using…
$this->mongo_db->where(array('_id'=>$estimate_id))->push("measurements", $newData)->update('estimates');
If I encode $newData using json_encode($newData) I get {"levels":[{"level_qty":12,"level_uom":"ft"}]}
The problem is, when my function creates the measurements line in the mongodb document, it automatically starts an array with my insertion at [0]. Like this…
"measurements" : [ { "levels" : [ { "level_qty" : 12, "level_uom" : "ft" } ] }]
…leaving me with…
-measurements
--0
----levels
-----0
------level_qty => 2,
------level_uom => ft
What I really want is…
-measurements
--levels
---0
----level_qty => 2,
----level_uom => ft
I’m certain I’m missing something fairly elementary (i.e. php related & not mongodb related), but I’m an admitted amateur who has waded too deep.
$push is used to append a value to an array. In your example,
measurementsis an array and Mongo is appending$newDataas its first element. This explains the0index betweenmeasurementsandlevels. In your desired result,measurementsis an object equivalent to$newData(i.e. it has alevelsproperty, which in turn has an array of objects within).Either of the following examples should accomplish what you want:
Note:
$pushis going to be more flexible if you want to append data with future updates, whereas$setwill naturally overwrite the given field.