gdoubleod
gdoubleod

Reputation: 1308

Inserting a PHP Object Into a MONGO DB

I have a php object that I would like to store in my Mongo database. What is the best way to store the object in the database? I was thinking of looping over the object and creating an array but this is a complex object that has sub objects as well. Thanks

Upvotes: 4

Views: 14041

Answers (3)

Ronaldo Cristover
Ronaldo Cristover

Reputation: 338

If you want save your value into Mongo Object ID:

$param = 'ojkhalskdjfhs9df87as08df';
$this->insert($collection, [
'aaaaa' => new MongoId($param)
]);

Upvotes: 0

xiaolong
xiaolong

Reputation: 3647

encode to JSON and insert to MongoDB.

Upvotes: 1

netcoder
netcoder

Reputation: 67695

The easiest way is probably to make your object "castable" to an array.

If the properties you want to store are public, you can just do:

$array = (array)$foo;

Otherwise, a toArray method, or making it implement an Iterator interface will work:

class Foo implements IteratorAggregate {

   protected $bar = 'hello';

   protected $baz = 'world';

   public function getIterator() {
       return new ArrayIterator(array(
           'bar' => $this->bar,
           'baz' => $this->baz,
       ));
   }

}

Obviously, you can also use get_object_vars, Reflection and such instead of hardcoding the property list in the getIterator method.

Then, just:

$foo = new Foo;
$array = iterator_to_array($foo);
$mongodb->selectCollection('Foo')->insert($array);

Depending on how you want to store your objects, you may want to use DBRefs instead of storing nested objects all at once, so you can easily find them separately afterwards. If not, just make your toArray method recursive.

Upvotes: 9

Related Questions