简体   繁体   中英

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

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.

编码为JSON并插入MongoDB。

If you want save your value into Mongo Object ID:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM