Skip to content
This repository has been archived by the owner on Jun 11, 2021. It is now read-only.

Mongo Functions

gwagner edited this page Dec 16, 2011 · 4 revisions

Function addToSet:

<?php
class Model_User extends Shanty_Mongo_Document
{
	public function appendPreferences($area, $key, $val = null, $save = true)
	{
		if(is_array($val))
			/* $each is required or else it will try to add the values as an actual array 
                           $each will insert all the values from the $val array into your $key ignoring any duplicates */
			$this->addToSet($area.'.'.$key, array('$each' => $val));
		else
                        /* This will add one value to the end of an array of values store in mongodb.  
                           It can only be called once per save. */
			$this->addToSet($area.'.'.$key, $val);


		if($save)
			$this->save();
	}
}

Function pull

Its important to remember pull always expects an array, even if you are only removing one object (as in the example below). The ->pull() method actually calls the mongo $pullAll method.

In this example we have two arrays 'upvoters' and 'down voters' a user can change their vote at any time, in this case voting down, we first make sure their ID is pulled from the list of upvoters (its fine if it isn't present in the array) and finally add it to the down voters array, ignoring if its already in the array.

<?php
$post->pull('upvoters', array($user->getID()));
$post->addToSet('downvoters', $user->getID());

$post->save();
Clone this wiki locally