Joomla Jumpstart

  • Increase font size
  • Default font size
  • Decrease font size
Home NoSQL Databases MongoDB How to append a Mongo array from PHP

How to append a Mongo array from PHP

E-mail Print PDF
User Rating: / 6
PoorBest 

MongoDB logoOne of the great things about Mongo is the ability to have arrays associated with a record without having to add an additional related table (as you do in a traditional database). In PHP, you can easily add an element to a Mongo database array with the $push command through either an update or an upsert.

 

To make an update (if the record already exists), use this command on your collection object:
$myCollection->update($queryArray, array('$push' => $newData ));

To make it an upsert (update if present, insert if not), use this:

$upsert = true; 
$myCollection->update($queryArray, array('$push' => $newData ), array("upsert" => $upsert));

That will add the information in $newData to the array. So to add a timestamp entry to an array of timestamps where there is an "id" column, you could use this command:

$myCollection->update(array('id'=>1), array('$push' => array('ts'=>time()) ), array("upsert" => $upsert));

The command will find the first record with an id of 1 and push the current timestamp into an array called"ts"and create it if it doesn't exist.

 

 
nico_charles RT @justinvincent: Goodbye, MongoDB http://t.co/cmFYMCTL
by nico_charles. Link: Pluggio
danailon RT @michaelklishin: So yes indeed, MongoDB is now just a feature in PostgreSQL 9.2 beta, thanks to just a few functions by @tobyhede https://t.co/SUt9FoGo
by danailon. Link: Twitter for Mac
tomassrnka RT @michaelklishin: So yes indeed, MongoDB is now just a feature in PostgreSQL 9.2 beta, thanks to just a few functions by @tobyhede https://t.co/SUt9FoGo
by tomassrnka. Link: Twitter for Mac
plopezFr RT @mongodb: Rejoignez nous le 14 Juin pour MongoDB Paris. La plupart des présentations seront en français ! http://t.co/iX8EHOPV
by plopezFr. Link: Buffer

Google AdSense


Coffee and Cream Publishing