Adding an Element to a Document’s Array Field in MongoDB using Lithium PHP


I’ve been using the Lithium PHP MVC framework because it has native drivers for MongoDB.  I’m writing a multiplayer Virtual World using MongoDB as it’s only backend DB, so I searched far and wide for a framework with  the type of Mongo dedication I found in Lithium.

The one thing Lithium is lacking at the moment is easy to follow documentation and tutorials, especially for the more advanced and foreign MongoDB operators.

In this case, I needed to add an item array to the User document’s “Item” array.  For this I need to use MongoDB’s $push operator.  After a ton of trial and error and googling, I finally got it working.  Here’s the syntax:

$user_id = '4b6eeb7df964a5200cd12ce3';
$item = array('_id'=>'4efeb26a33f5681d7a000000', 'name'=>'Item Name');
$conditions = array('_id' => $user_id);
$query = array('$push'=> array('Items'=>$item));
Users::update($query, $conditions);

That’s it.  Thank you drive though.


SysOp
SysOp
This is the description

Leave a Reply